Zachary W. Huang

Home Projects Blog Guides Resume

Prototype

Idea: Generalize the usage of objects by specifying a prototypical instance and creating clones when needed. Can be used to greatly decouple a system from how its products are created, composed, and represented.

abstract class Product {
  abstract clone(): Product;
}

class ThingOne extends Product {
  clone() {
    // copy of self
    return {} as ThingOne;
  }
}
class ThingTwo extends Product {
  clone() {
    // copy of self
    return {} as ThingTwo;
  }
}

class Creator {
  protoThingOne: Product;
  protoThingTwo: Product;

  constructor(protoThingOne: ThingOne, protoThingTwo: ThingOne) {
    this.protoThingOne = protoThingOne;
    this.protoThingTwo = protoThingTwo;
  }

  doThing() {
    let thingOne = this.protoThingOne.clone();
    let thingTwo = this.protoThingTwo.clone();
    console.log(thingOne, thingTwo)
  }
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024