Topic:
-객체 생성 로직을 client로 부터 감춘채, common interface를 통하여 새로생성된 객체를 참조한다.
public interface Shape { void draw(); } 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; } }
public class Circle implements Shape { private final String TAG = Circle.class.getSimpleName(); @Override public void draw() { Log.d(TAG, "Circle draw"); } } public class Rectangle implements Shape { private final String TAG = Rectangle.class.getSimpleName(); @Override public void draw() { Log.d(TAG, "Rectangle draw"); } } public class Square implements Shape { private final String TAG = Square.class.getSimpleName(); @Override public void draw() { Log.d(TAG, "Square draw"); } }
결과 :
-application(client)가 Factory객체를 통해 객체를 간접적으로 획득, interface를 활용한 method 호출
ShapeFactory shapeFactory= new ShapeFactory(); Shape a =shapeFactory.getShape("circle"); a.draw(); a=shapeFactory.getShape("rectangle"); a.draw(); a=shapeFactory.getShape("square"); a.draw();
07-17 17:18:40.666 22057 22057 D Circle : Circle draw
07-17 17:18:40.667 22057 22057 D Rectangle: Rectangle draw
07-17 17:18:40.667 22057 22057 D Square : Square draw
출처 :
https://www.tutorialspoint.com//design_pattern/design_pattern_quick_guide.htm
'pattern' 카테고리의 다른 글
Prototype pattern (0) | 2018.07.18 |
---|---|
Builder pattern (0) | 2018.07.18 |
Singleton pattern (0) | 2018.07.18 |
Abstract Factory Pattern (0) | 2018.07.18 |
Type of Design Pattern (0) | 2018.07.17 |