Prototype

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests

Source Code Listing

code.ts

type Prototype = {
  clone(): Prototype;
  setProperty(property: string): void;
  logProperty(): void;
};

class ConcretePrototype1 implements Prototype {
  property: string | undefined; // Make property optional

  clone(): ConcretePrototype1 {
    const cloned = new ConcretePrototype1();
    cloned.property = this.property; // Deep copy of property
    return cloned;
  }

  setProperty(property: string): void {
    this.property = property;
  }

  logProperty(): void {
    console.log(this.property ?? "-");
  }
}

class ConcretePrototype2 implements Prototype {
  property: string | undefined;

  clone(): ConcretePrototype2 {
    const cloned = new ConcretePrototype2();
    cloned.property = this.property;
    return cloned;
  }

  setProperty(property: string): void {
    this.property = property;
  }

  logProperty(): void {
    console.log(this.property || "-");
  }
}

class Client {
  operation(prototype: Prototype): Prototype {
    return prototype.clone();
  }
}

const example = {
  run(): void {
    const client = new Client();
    const cp1 = new ConcretePrototype1();
    const cp1Prototype = client.operation(cp1);

    cp1.setProperty("original1");
    cp1Prototype.setProperty("clone1");
    cp1.logProperty();
    cp1Prototype.logProperty();

    const cp2 = new ConcretePrototype2();
    const cp2Prototype = client.operation(cp2);

    cp2.setProperty("original2");
    cp2Prototype.setProperty("clone2");
    cp2.logProperty();
    cp2Prototype.logProperty();
  },
};

example.run();