Flyweight pattern
-생성되는 객체의 수를 감소시키고, 메모리 사용량을 감소시켜 performance를 증대 시킴.
-객체 구조를 향상시키고 갯수를 감소시키는 structural pattern.
-이미 존재하는 유사한 객체를 저장하고 재사용함, 만일 매칭되는 객체가 없을 경우에 객체를 생성함.
Main 호출 부
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | Circle s = (Circle) ShapeFactory.getCircle( "red" ); s.setRadius( 10 ); s.setX( 10 ); s.setY( 10 ); s.draw(); s=(Circle)ShapeFactory.getCircle( "green" ); s.setRadius( 9 ); s.setX( 9 ); s.setY( 9 ); s.draw(); s=(Circle)ShapeFactory.getCircle( "blue" ); s.setRadius( 11 ); s.setX( 11 ); s.setY( 11 ); s.draw(); s=(Circle)ShapeFactory.getCircle( "red" ); s.draw(); s=(Circle)ShapeFactory.getCircle( "green" ); s.draw(); s=(Circle)ShapeFactory.getCircle( "blue" ); s.draw(); |
ShapeFactory를 아래와 같이 구성한다. CircleMap을 두어 class level에서 생성된 Circle객체를 관리한다. 이미 생성된 적이 있는 객체의 경우는 다시 객체 생성을 하지 않는다.
ShapeFactory.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class ShapeFactory { private static HashMap CircleMap = new HashMap(); public static Shape getCircle(String color){ Circle circle = (Circle)CircleMap.get(color); if (circle == null ){ circle = new Circle(color); CircleMap.put(color, circle); Log.d( "shape" , "Create circle : color =" +color); } return circle; } } |
나머지:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public interface Shape { void draw(); } public class Circle implements Shape { private String color; private int x; private int y; private int radius; public Circle(String color){ this .color=color; } private final String TAG = Circle. class .getSimpleName(); @Override public void draw() { Log.d(TAG, "Circle color =" +color+ " x :" +x+ " y :" +y + " radius : " +radius); } public void setX( int x) { this .x = x; } public void setY( int y) { this .y = y; } public void setRadius( int radius) { this .radius = radius; } } |
결과:
07-20 14:18:00.288 12348 12348 D shape : Create circle : color =red
07-20 14:18:00.288 12348 12348 D Circle : Circle color =red x :10 y :10 radius : 10
07-20 14:18:00.288 12348 12348 D shape : Create circle : color =green
07-20 14:18:00.288 12348 12348 D Circle : Circle color =green x :9 y :9 radius : 9
07-20 14:18:00.288 12348 12348 D shape : Create circle : color =blue
07-20 14:18:00.288 12348 12348 D Circle : Circle color =blue x :11 y :11 radius : 11
07-20 14:18:00.288 12348 12348 D Circle : Circle color =red x :10 y :10 radius : 10
07-20 14:18:00.288 12348 12348 D Circle : Circle color =green x :9 y :9 radius : 9
07-20 14:18:00.288 12348 12348 D Circle : Circle color =blue x :11 y :11 radius : 11
참조 :
https://www.tutorialspoint.com/design_pattern/flyweight_pattern.htm
'pattern' 카테고리의 다른 글
Chain of Responsibility Pattern (0) | 2018.07.20 |
---|---|
Proxy Pattern (0) | 2018.07.20 |
Facade Pattern (0) | 2018.07.20 |
Decorator pattern (0) | 2018.07.20 |
uml 기호 정리 (0) | 2018.07.20 |