The Flyweight Pattern is a structural design pattern that minimizes memory usage
by sharing common parts of objects while allowing unique variations. This
pattern is particularly useful when working with a large number of similar
objects,
improving performance and reducing resource consumption.
typeFlyweight={operation(extrinsicState: string):void;};classConcreteFlyweightimplementsFlyweight{privateintrinsicState="";// Initialize intrinsicState
constructor(privatereadonlykey: string){}// Key is now private and set in constructor
operation(extrinsicState: string):void{this.intrinsicState+=`${extrinsicState} `;console.log(`Flyweight ${this.key}: ${this.intrinsicState}`);}}classUnsharedConcreteFlyweightimplementsFlyweight{allState: any=null;// Initialize allState
operation(extrinsicState: string):void{// Unshared flyweights don't typically share intrinsic state
// They might use the extrinsic state differently or maintain their own state
this.allState=extrinsicState;console.log("Unshared Flyweight:",this.allState);}}classFlyweightFactory{privatereadonlyflyweights: Record<string,Flyweight>={};getFlyweight(key: string):Flyweight{this.flyweights[key]||=newConcreteFlyweight(key);returnthis.flyweights[key];}getUnsharedFlyweight():UnsharedConcreteFlyweight{returnnewUnsharedConcreteFlyweight();}}constclient={run():void{constfactory=newFlyweightFactory();constfoo=factory.getFlyweight("foo");constbar=factory.getFlyweight("bar");constbaz=factory.getFlyweight("baz");constqux=factory.getFlyweight("foo");// Same instance as 'foo'
foo.operation("red");// Modifies the shared intrinsic state
bar.operation("green");baz.operation("blue");qux.operation("black");// Affects the shared intrinsic state of 'foo'
constunsharedFlyweight1=factory.getUnsharedFlyweight();constunsharedFlyweight2=factory.getUnsharedFlyweight();unsharedFlyweight1.operation("state1");unsharedFlyweight2.operation("state2");}};client.run();