Bibi's DevLog π€π
[Java] ν©ν 리 λ©μλ ν¨ν΄(κΈ°μ΄) λ³Έλ¬Έ
π₯ BE λ°±μλ/Java μλ°
[Java] ν©ν 리 λ©μλ ν¨ν΄(κΈ°μ΄)
λΉλΉ bibi 2021. 3. 2. 23:43ν©ν 리 λ©μλ
ν©ν 리 λ©μλ ν¨ν΄ Factory Method Pattern μ΄λ?
μλ° λμμΈν¨ν΄μ νλλ‘, κ°μ²΄ μμ±μ λμ μνν΄ μ£Όλ 곡μ₯μ λΉμ ν μ μλ€.
κ°μ²΄λ₯Ό μ§μ μμ±νλ λμ , λ©μλλ₯Ό ν΅ν΄ κ°μ μ μΌλ‘ μμ± ν λ°ννλ λ°©μ.
(κ°μ μ μΌλ‘ κ°μ²΄λ₯Ό λμ μμ±ν΄ μ£Όλ λ©μλλ₯Ό ν©ν 리λ©μλλΌκ³ νλ€)
μ₯μ
- μμ±ν ν΄λμ€λ₯Ό 미리 μμ§ λͺ»ν΄λ ν©ν 리 ν΄λμ€κ° κ°μ²΄ μμ±μ λ΄λΉν΄ μ€λ€.
- κ°μ²΄μ μλ£νμ΄ νμν΄λμ€μ μν΄ κ²°μ λλ€ - νμ₯μ΄ μ©μ΄νλ€
- νμ₯μ± μλ μ 체 νλ‘μ νΈλ₯Ό ꡬμ±ν μ μλ€.
- λμΌν ννλ‘ νλ‘κ·Έλλ°μ΄ κ°λ₯νλ€.
λ¨μ
- κ°μ²΄κ° λμ΄λ λ λ§λ€ νμν΄λμ€λ₯Ό μ¬μ μν΄μΌ νλ―λ‘ λΆνμν λ§μ ν΄λμ€κ° μμ±λ μ μλ€.
μμ
Shape.java
public interface Shape {
void draw();
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle - draw() Method.");
}
}
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle - draw() Method.");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Square - draw() Method.");
}
}
ShapeFactory.java
public class ShapeFactory {
// ν©ν 리 λ©μλ - κ°μ²΄ μμ± ν λ°ν
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
FactoryPatternTest.java
public class FactoryPatternTest {
public static void main(String[] args) {
// ν©ν 리 ν΄λμ€μμ κ°μ²΄λ₯Ό μμ± ν λ°ν
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw(); // Circle λ©μλ νΈμΆ
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw(); // Rectangle λ©μλ νΈμΆ
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw(); // Square λ©μλ νΈμΆ
}
}
μΆμ² : ν°μ€ν 리 λΈλ‘κ·Έ. κ°μ¬ν©λλ€!