Factory method
μΈν°νμ΄μ€λ‘ κ°μ²΄λ€μ μ μνκ³ , ν©ν λ¦¬κ° μΈμ€ν΄μ€λ₯Ό μμ±
κ°μ²΄λ₯Ό μμ±νλ μ½λλ₯Ό λΆλ¦¬μν΄μΌλ‘ ν΄λΌμ΄μΈνΈ μ½λμ κ²°ν©λ(μμ‘΄μ±)λ₯Ό π
π μ½λ λ³κ²½ μ, κ°μ²΄ μμ± ν΄λμ€λ§ μμ κ°λ₯
μΈν°νμ΄μ€λ₯Ό λ°νμΌλ‘ μ μ°μ±κ³Ό νμ₯μ±μ΄ λ°μ΄λ μ½λ ꡬν κ°λ₯
κ°μ²΄μ μλ£νμ΄ νμ ν΄λμ€μ μν΄ κ²°μ
π νμ₯ μ©μ΄
SOLID μμΉ μ€ DIP(Dependency Inversion Principle, μμ‘΄ κ΄κ³ μμ μμΉ) μ±λ¦½
ꡬ쑰
Code
public class FactoryPatternEx {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
}
}
π Factoryμμ λ§λ€μ΄λΌ μνλ€μ μ μ
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
π μνλ€μ λ§λ€μ΄ λ΄λ³΄λΌ ν©ν 리 μ μ
public class ShapeFactory {
public Shape getShape(String shapeType) {
if (ShapeType.equalsIgnoreCase("CIRCLE"))
return new Circle();
else if (ShapeType.equalsIgnoreCase("RECTANGLE"))
return new Rectangle();
else
return null
}
}