FlyWeight Pattern ?
변하지 않는 속성은 재사용하여 메모리 사용량을 최소화하는 디자인 패턴
구성
- Flyweight : 공유에 사용되는 클래스들의 인터페이스 선언
- ConcreteFlyweight : 실공유 객체
- FlyweightFactory : Flywieght 인스턴스를 생성 또는 공유
- Client
// Flyweight
public interface Shape {
public void draw();
}
// ConcreteFlyweight
public class Circle implements Shape {
private String color;
private int radius;
public Circle(String color) {
this.color = color;
}
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle color="+", raidus="+radius);
}
}
// WeightFactory
public class ShapeFactory {
private static final HashMap<String ,Circle> 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("#### create new circle => "+color);
}
return circle;
}
}
// client
public class Main {
... main code
String[] colors = {"RED", "GREEN", "PINK"}
for(int i=0; i<10; i++) {
Circle circle =(Circle)ShapeFactory.getCircle(colors[(int)Math.random()*3)]);
circle.setRadius((int) (Math.random()*10));
circle.draw();
}
}
결과로 같은 색상의 원은 1개만 생성되며 radius 값만 변경되는 것을 확인 할 수 있다 (생성된 객체는 공유 됨)
장단점
- 객체 인스턴스 줄여서 메모리 절약
- 특정 인스턴스만 다른 인스턴스처럼 동작하도록 하는 것은 불가능 => 자주 변하지 않는 속성일 경우 권장
Singleton Pattern과의 차이
- Singleton은 클래스 자체가 오직 1개의 인스턴스만 허용
- Flyweight는 클래스 팩토리에서 제어