Flyweight Pattern

Posted by Dustin Boston in .

The Flyweight Pattern is a structural design pattern that reduces memory usage by sharing common parts of objects while maintaining unique variations.


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.

Source Code Listing

code.ts

type Flyweight = {
  operation(extrinsicState: string): void;
};

class ConcreteFlyweight implements Flyweight {
  private intrinsicState = ""; // Initialize intrinsicState

  constructor(private readonly key: string) {} // Key is now private and set in constructor

  operation(extrinsicState: string): void {
    this.intrinsicState += `${extrinsicState} `;
    console.log(this.intrinsicState);
  }
}

class UnsharedConcreteFlyweight implements Flyweight {
  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);
  }
}

class FlyweightFactory {
  private readonly flyweights: Record<string, Flyweight> = {};

  getFlyweight(key: string): Flyweight {
    this.flyweights[key] ||= new ConcreteFlyweight(key);

    return this.flyweights[key];
  }

  getUnsharedFlyweight(): UnsharedConcreteFlyweight {
    return new UnsharedConcreteFlyweight();
  }
}

const client = {
  run(): void {
    const factory = new FlyweightFactory();
    const foo = factory.getFlyweight("foo");
    const bar = factory.getFlyweight("bar");
    const baz = factory.getFlyweight("baz");
    const qux = 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'

    const unsharedFlyweight1 = factory.getUnsharedFlyweight();
    const unsharedFlyweight2 = factory.getUnsharedFlyweight();

    unsharedFlyweight1.operation("state1");
    unsharedFlyweight2.operation("state2");
  },
};

client.run();