class AbstractBox {
constructor() {
console.log('Flyweight Class created');
}
getShape() {
throw new Error("This method must be overwritten!");
}
display(color) {
console.log("方块颜色:" + color);
}
}
class BoxFactory {
constructor() {
console.log('FlyweightFactory Class created');
}
static getBox(key) {
if(!this.flyweights[key]){
switch (key) {
case 'I':
this.flyweights[key] = new IBox();
break;
case 'L':
this.flyweights[key] = new LBox();
break;
case 'O':
this.flyweights[key] = new OBox();
break;
default:
throw new Error("The Linux distribution you are looking for has not been found");
}
}
return this.flyweights[key];
}
static createGibberish(){
return new UnsharedBox();
}
}
BoxFactory.flyweights = {};
class UnsharedBox extends AbstractBox {
getShape() {
console.log('我是不共享的享元对象')
}
}
// I形方块
class IBox extends AbstractBox {
getShape() {
return "I";
}
}
// L形方块
class LBox extends AbstractBox {
getShape() {
return "L";
}
}
// O形方块
class OBox extends AbstractBox {
getShape() {
return "O";
}
}
let i1 = BoxFactory.getBox("I");
console.log(111111)
i1.display('red');
let i2 = BoxFactory.getBox("L");
i2.display('blue');
let i3 = BoxFactory.getBox("O");
i3.display('green');
let i4 = BoxFactory.getBox("O");
i4.display('yellow');
// 也可以更改外观状态
i4.display('grey');
// 用 == 对比两个对象
console.log("两个对象是否相等:" + (i3 == i4));
// 对于非享元对象的调用
let unsharebox = BoxFactory.createGibberish();
console