1.2 Abstract Factory Pattern
-factory of factories.
-Creational pattern 중 객체를 생성하는 가장 좋은 방법 중 하나이다.
-Abstract Factory pattern은 명시적 객체 지정 없이 관련된 factory를 주는 역할을 하는 interface이다.
-Factory와 마찬가지로 어떤 factory객체를 인자로 넘겨줄지에 대한 고민을 덜어내어 common한 구조로 가는데 도움이 된다.
-이렇게 각각 생성된 factory는 또다시 factory pattern을 따라 객체를 생성한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | AbstractFactory shapeFactory = FactoryProducer.getFactory("Shape");Shape s = shapeFactory.getShape("rectangle");s.draw();s = shapeFactory.getShape("Circle");s.draw();s = shapeFactory.getShape("square");AbstractFactory colorFactory = FactoryProducer.getFactory("Color");Color c = colorFactory.getColor("red");c.fill();c = colorFactory.getColor("blue");c.fill();c = colorFactory.getColor("green");c.fill(); |
FactoryProducer.java
1 2 3 4 5 6 7 8 9 10 11 12 | public class FactoryProducer { public static AbstractFactory getFactory(String choice){ if(choice.equalsIgnoreCase("shape")) return new ShapeFactory(); else if (choice.equalsIgnoreCase("color")) return new ColorFactory(); else return null; }} |
AbstractFactory.java
1 2 3 4 | public abstract class AbstractFactory { public abstract Color getColor(String color); public abstract Shape getShape(String shape);} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class ShapeFactory extends AbstractFactory { @Override 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; } @Override public Color getColor(String color) { return null; }} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class ColorFactory extends AbstractFactory { @Override public Color getColor(String color) { if (color.equalsIgnoreCase(("red"))) return new Red(); else if (color.equalsIgnoreCase(("blue"))) return new Blue(); else if (color.equalsIgnoreCase(("green"))) return new Green(); return null; } @Override public Shape getShape(String shape) { return null; }} |
출처 :
https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm
'pattern' 카테고리의 다른 글
| Prototype pattern (0) | 2018.07.18 |
|---|---|
| Builder pattern (0) | 2018.07.18 |
| Singleton pattern (0) | 2018.07.18 |
| factory pattern (0) | 2018.07.17 |
| Type of Design Pattern (0) | 2018.07.17 |