9.享元模式
享元模式(Flyweight Pattern)的主要目的是通过共享可复用的内部状态,减少大量相似对象的内存占用
适合使用享元模式的场景
- 系统中存在大量细粒度对象,且大部分状态可共享
- 对象创建和存储成本高,内存压力明显
- 可以明确拆分“内部状态”和“外部状态”
- 希望通过对象池或缓存提升资源复用率
共享对象定义
type PieceColor = "black" | "white";
class ChessPieceType {
constructor(
public readonly name: string,
public readonly color: PieceColor,
) {}
}享元工厂与上下文对象
class ChessPieceFactory {
private static pool = new Map<string, ChessPieceType>();
static get(name: string, color: PieceColor): ChessPieceType {
const key = `${name}-${color}`;
if (!this.pool.has(key)) {
this.pool.set(key, new ChessPieceType(name, color));
}
return this.pool.get(key)!;
}
static size(): number {
return this.pool.size;
}
}
class ChessPiece {
constructor(
private readonly type: ChessPieceType,
private x: number,
private y: number,
) {}
draw(): void {
console.log(`${this.type.color} ${this.type.name} at (${this.x}, ${this.y})`);
}
}使用示例
const p1 = new ChessPiece(ChessPieceFactory.get("pawn", "white"), 1, 2);
const p2 = new ChessPiece(ChessPieceFactory.get("pawn", "white"), 2, 2);
const p3 = new ChessPiece(ChessPieceFactory.get("pawn", "black"), 1, 7);
p1.draw();
p2.draw();
p3.draw();
console.log("共享对象数量:", ChessPieceFactory.size()); // 2