1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| class Flyweight { private sharedState: any;
constructor(sharedState: any) { this.sharedState = sharedState; }
public operation(uniqueState): void { const s = JSON.stringify(this.sharedState); const u = JSON.stringify(uniqueState); console.log(`Flyweight: Displaying shared (${s}) and unique (${u}) state.`); } } class FlyweightFactory { private flyweights: {[key: string]: Flyweight} = <any>{};
constructor(initialFlyweights: string[][]) { for (const state of initialFlyweights) { this.flyweights[this.getKey(state)] = new Flyweight(state); } }
private getKey(state: string[]): string { return state.join('_'); }
public getFlyweight(sharedState: string[]): Flyweight { const key = this.getKey(sharedState);
if (!(key in this.flyweights)) { console.log('FlyweightFactory: Can\'t find a flyweight, creating new one.'); this.flyweights[key] = new Flyweight(sharedState); } else { console.log('FlyweightFactory: Reusing existing flyweight.'); }
return this.flyweights[key]; }
public listFlyweights(): void { const count = Object.keys(this.flyweights).length; console.log(`\nFlyweightFactory: I have ${count} flyweights:`); for (const key in this.flyweights) { console.log(key); } } }
const factory = new FlyweightFactory([ ['Chevrolet', 'Camaro2018', 'pink'], ['Mercedes Benz', 'C300', 'black'], ['Mercedes Benz', 'C500', 'red'], ['BMW', 'M5', 'red'], ['BMW', 'X6', 'white'], ]); factory.listFlyweights();
|