플라이웨이트 패턴(Flyweight Pattern)은 수많은 동일한(또는 매우 유사한) 객체들을 생성할 때, 객체 내부의 공통된 데이터를 공유함으로써 메모리 낭비를 극적으로 줄이는 구조 패턴입니다.
마인크래프트 같은 게임에서 수만 개의 '나무 블록'을 그릴 때, 텍스처 이미지나 색상 같은 '변하지 않는 속성(Intrinsic)'은 한 번만 메모리에 올린 뒤 모든 블록이 공유합니다. 그리고 좌표(X,Y,Z) 같은 '각각 다른 속성(Extrinsic)'만 외부에서 받아 처리하여 OutOfMemory(메모리 초과) 에러를 방지합니다.
📐 Flyweight Pattern UML
플라이웨이트 패턴은 본질적(Intrinsic) 상태를 공유하여 수많은 객체를 생성할 때 발생하는 메모리 낭비를 방지합니다.
class TreeType {
constructor(name, color, texture) {
this.name = name; this.color = color; this.texture = texture;
}
draw(x, y) { console.log(`나무 그리기: [${this.name}, ${this.color}] at (${x}, ${y})`); }
}
class TreeFactory {
static treeTypes = {};
static getTreeType(name, color, texture) {
const key = `${name}_${color}_${texture}`;
if (!this.treeTypes[key]) {
this.treeTypes[key] = new TreeType(name, color, texture);
}
return this.treeTypes[key];
}
}
class Tree {
constructor(x, y, type) {
this.x = x; this.y = y; this.type = type;
}
draw() { this.type.draw(this.x, this.y); }
}
const trees = [];
const pineType = TreeFactory.getTreeType("소나무", "초록", "거친질감");
trees.push(new Tree(10, 20, pineType));
trees.push(new Tree(50, 60, pineType));
for (const tree of trees) tree.draw();