// 享元模式 就是 对象池 共享对象
abstract class AA {
protected intrinsic: string = null; //内部的
protected extrinsic: string = null; //外部的
constructor(extrinsic: string) {
YBLog.log("Test", " 17 构造函数");
this.extrinsic = extrinsic;
}
abstract operate(): string;
public getIntrinsic() {
return this.intrinsic
}
public setIntrinsic(intrinsic: string) {
this.intrinsic = intrinsic;
}
}
class aaa extends AA {
operate(): string {
return "AA ";
}
}
//具体的构件
class Factory {
private myMap = new Map();
public getSingleInstance(key: string): AA {
let ss: AA = null;
if (this.myMap.has(key)) {
ss = this.myMap.get(key);
YBLog.log( "Test"," 42 42 使用旧的 ");
} else {
ss = new aaa(key);
this.myMap.set(key,ss);
YBLog.log( "Test"," 47 47 新建的 ");
}
return ss ;
}
public removeSingleInstance(key: string )
{
this.myMap.delete(key);
YBLog.log( "Test", "54 54 剩余数量 :" , this.myMap.size);
}
}
let factory:Factory = new Factory();
factory.getSingleInstance( "aaa" ).operate();
factory.getSingleInstance( "bbb" ).operate();
factory.getSingleInstance( "aaa" ).operate();
factory.removeSingleInstance("aaa");
//优点: 共享对象
//缺点:
来源:oschina
链接:https://my.oschina.net/u/4381258/blog/4647535