Zachary W. Huang

Home Projects Blog Guides Resume

Flyweight

Idea: represent a large number of objects using a smaller number of shared (but context-independent) objects.

Connection: Similar to the concept of immutability - we can safely share memory (objects) as long as they are guaranteed to never change over time.

class Flyweight {
  intrinsicState: string;

  constructor(intrinsicState: string) {
    this.intrinsicState = intrinsicState;
  }

  doThing(extrinsicState: string) {
    console.log(this.intrinsicState + extrinsicState);
  };
}

class FlyweightFactory {
  pool: Record<string, Flyweight> = {}

  getFlyweight(key: string) {
    if (key in this.pool) {
      return this.pool[key];
    } else {
      this.pool[key] = new Flyweight(key);
      return this.pool[key];
    }
  }
}

function main() {
  const factory = new FlyweightFactory();

  // each of these objects is "backed" by the same flyweight
  const thingA = factory.getFlyweight("A");
  const thingB = factory.getFlyweight("A");
  const thingC = factory.getFlyweight("A");
  thingA.doThing("1"); // "A1"
  thingB.doThing("2"); // "A2"
  thingC.doThing("3"); // "A3"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024