[구조 패턴] Flyweight pattern (플라이웨이트 패턴)
어떤 클래스의 인스턴스 한 개만가지고 여러 개의 "가상 인스턴스"를 제공하고 싶을 때
팩토리패턴과 비슷하나 생성목록에 없는 새로운 것을 만들경우 이벤트를 추가한다.
(ex.이미 가지고 있던 아이템의 타입 이외의 것이 추가되었을 경우 N마크 추가하는 등의 이벤트)
플라이웨이트 패턴은 주로 생성 된 객체 수를 줄이고 메모리 사용 공간을 줄이며 성능을 향상시키는 데 사용됩니다. 이러한 유형의 디자인 패턴은 오브젝트 패턴을 감소시켜 어플리케이션에 필요한 오브젝트 구조를 향상시키는 방법을 제공하기 때문에 구조 패턴에 속합니다.
플라이급 패턴은 이미 존재하는 비슷한 종류의 객체를 저장하여 재사용을 시도하고 일치하는 객체가 발견되지 않으면 새로운 객체를 만듭니다. 우리는 20 개의 다른 위치의 원을 그려서이 패턴을 시연 할 것이지만 우리는 5 개의 객체 만 만들 것입니다. 5 가지 색상 만 사용할 수 있으므로 기존 Circle 객체를 확인하는 데 color 속성이 사용됩니다.
Implementation
Shape 인터페이스와 Shape 인터페이스를 구현하는 구체적인 Circle 클래스를 생성할 것이다. ShapeFactory 클래스는 다은단계에 정의되어 진다.
ShapeFactory는 Circle객체의 색을 key로 갖는 Circle의 HashMap을 갖는다. ShapeFactory로 특정색의 원을 생성하기 위한 요청이 올때마다 HashMap에서 circle객체를 점검한다. 만약 Circle의 객체를 찾으면 그 객체는 반환되어지지만 그렇지 않으면 새로운 객체가 생성, 앞으로의 사용을 위해 저장되고 클라이언트로 반환된다.
FlyWeightPatternDeom, demo 클래스는 Shape객체를 얻기 위해 ShapeFactory를 사용할 것이다. 이는 희망하는 색의 원을 얻기위해 ShapeFactory로 정보(red/green/blue/black/white)를 전달할 것이다.
Step 1
인터페이스를 생성한다.
Shape.java
public interface Shape { void draw(); }
Step 2
동일 인터페이스를 구현하는 구체적 클래스를 생성한다.
Circle.java
public class Circle implements Shape { private String color; private int x; private int y; private int radius; public Circle(String color){ this.color = color; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setRadius(int radius) { this.radius = radius; } @Override public void draw() { System.out.println("Circle: Draw() [Color : " + color + ", x : " + x + ", y :" + y + ", radius :" + radius); } }
Step 3
주어진 정보를 기초로 구체적인 클래스의 객체를 생성하기 위한 factory를 생성한다.
ShapeFactory.java
import java.util.HashMap; public class ShapeFactory { private static final HashMap<String, Shape> 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); System.out.println("Creating circle of color : " + color); } return circle; } }
Step 4
색같은 정보를 전달하는 것으로 구체적인 클래스의 객체를 얻기위해 factory를 사용한다.
FlyweightPatternDemo.java
public class FlyweightPatternDemo { private static final String colors[] = { "Red", "Green", "Blue", "White", "Black" }; public static void main(String[] args) { for(int i=0; i < 20; ++i) { Circle circle = (Circle)ShapeFactory.getCircle(getRandomColor()); circle.setX(getRandomX()); circle.setY(getRandomY()); circle.setRadius(100); circle.draw(); } } private static String getRandomColor() { return colors[(int)(Math.random()*colors.length)]; } private static int getRandomX() { return (int)(Math.random()*100 ); } private static int getRandomY() { return (int)(Math.random()*100); } }
Step 5
결과를 확인한다.
Creating circle of color : Black Circle: Draw() [Color : Black, x : 36, y :71, radius :100 Creating circle of color : Green Circle: Draw() [Color : Green, x : 27, y :27, radius :100 Creating circle of color : White Circle: Draw() [Color : White, x : 64, y :10, radius :100 Creating circle of color : Red Circle: Draw() [Color : Red, x : 15, y :44, radius :100 Circle: Draw() [Color : Green, x : 19, y :10, radius :100 Circle: Draw() [Color : Green, x : 94, y :32, radius :100 Circle: Draw() [Color : White, x : 69, y :98, radius :100 Creating circle of color : Blue Circle: Draw() [Color : Blue, x : 13, y :4, radius :100 Circle: Draw() [Color : Green, x : 21, y :21, radius :100 Circle: Draw() [Color : Blue, x : 55, y :86, radius :100 Circle: Draw() [Color : White, x : 90, y :70, radius :100 Circle: Draw() [Color : Green, x : 78, y :3, radius :100 Circle: Draw() [Color : Green, x : 64, y :89, radius :100 Circle: Draw() [Color : Blue, x : 3, y :91, radius :100 Circle: Draw() [Color : Blue, x : 62, y :82, radius :100 Circle: Draw() [Color : Green, x : 97, y :61, radius :100 Circle: Draw() [Color : Green, x : 86, y :12, radius :100 Circle: Draw() [Color : Green, x : 38, y :93, radius :100 Circle: Draw() [Color : Red, x : 76, y :82, radius :100 Circle: Draw() [Color : Blue, x : 95, y :82, radius :100
'Development > Java' 카테고리의 다른 글
[행위 패턴] Mediator pattern (미디에이터 패턴) (0) | 2017.03.26 |
---|---|
[행위 패턴] Interpreter pattern (인터프리터 패턴) (0) | 2017.03.26 |
[행위 패턴] Chain of responsibility pattern (역할 사슬 패턴) (0) | 2017.03.26 |
[생성 패턴] Builder pattern (빌더 패턴) (0) | 2017.03.26 |
[구조 패턴] Bridge pattern (브리지 패턴) (0) | 2017.03.26 |