개발/디자인 패턴
구조 - 플라이웨이트(Flyweight)
제로칼로리
2023. 5. 9. 16:28
정의
flyweight는 다른 유사한 개체와 가능한 한 많은 데이터를 공유하여 메모리 사용을 최소화하는 패턴
하나의 인스턴스만으로 상태값만 변경해가며, 사용
주 목적은 메인메모리(RAM) 절약
코드
import java.time.LocalDate;
import java.time.Month;
public class FlyweightEx {
//공통 인터페이스
static interface Tree {
public void display(int x, int y);
public default boolean isWithinRange(LocalDate aDate) {
Month month = aDate.getMonth();
return (month.getValue() > 2) && (month.getValue() < 11);
}
}
static class ConiferTree implements Tree {
public void display(int x, int y) {
System.out.println("침엽수 위치 : " + x + ", " + y);
}
}
static class DeciduousTree implements Tree {
public void display(int x, int y) {
System.out.println("낙엽수 위치 : " + x + ", " + y);
if (!this.isWithinRange(LocalDate.now())) {
System.out.println("현재 계절엔 낙엽이 없습니다.");
}
}
}
//팩토리로 생성을 관리
static class TreeFactory {
Tree d, c = null;
public TreeFactory() {
this.d = new DeciduousTree();
this.c = new ConiferTree();
}
public Tree getTree(String type) throws Exception {
if (type.equals("침엽수")) {
return this.d;
} else if (type.equals("낙엽수")) {
return this.c;
} else {
throw new Exception("지원하지 않는 종류");
}
}
}
public static void main(String[] args) {
//플레이웨이트 클래스에서 상태만을 때어 별도로 관리
//상태가 바뀔때마다 마치 새로운 인스턴스 처럼 보이지만, 하나의 인스턴스
int[][] deciduousLocations = {{1, 1}, {33, 50}, {100, 90}};
int[][] coniferLocations = {{10, 87}, {24, 76}, {2, 64}};
TreeFactory treeFactory = new TreeFactory();
Tree d, c;
try {
d = treeFactory.getTree("낙엽수");
c = treeFactory.getTree("침엽수");
for (int[] location : deciduousLocations) {
d.display(location[0], location[1]);
}
for (int[] location : coniferLocations) {
c.display(location[0], location[1]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
결과
침엽수 위치 : 1, 1
침엽수 위치 : 33, 50
침엽수 위치 : 100, 90
낙엽수 위치 : 10, 87
낙엽수 위치 : 24, 76
낙엽수 위치 : 2, 64
웹 프로그래밍에선 쓰이는 곳을 찾기가 더 힘들 듯하다.