⭐프로토타입 패턴

상속 관계 (의존성) 없이 객체를 복사해서 사용하는 객체

실제 적용 예시

  • 인스턴스가 아니기 때문에 메서드에 아예 새로운 기능을 오버라이딩 하는것에 부담이 없다.
namespace PrototypePattern {
  export interface Prototype {
    clone(): Prototype;
    toString(): string;
  }

  export class Concrete1 implements Prototype {
    clone(): Prototype {
      return new Concrete1();
    }

    toString(): string {
      return "This is Concrete1";
    }
  }

  export class Concrete2 implements Prototype {
    clone(): Prototype {
      return new Concrete2();
    }

    toString(): string {
      return "This is Concrete2";
    }
  }

  export class Concrete3 implements Prototype {
    clone(): Prototype {
      return new Concrete3();
    }

    toString(): string {
      return "This is Concrete3";
    }
  }

  export class Builder {
    private prototypeMap: { [s: string]: Prototype } = {};

    constructor() {
      this.prototypeMap["c1"] = new Concrete1();
      this.prototypeMap["c2"] = new Concrete2();
      this.prototypeMap["c3"] = new Concrete3();
    }

    createOne(s: string): Prototype {
      console.log(s);
      return this.prototypeMap[s].clone();
    }
  }
}

export function show(): void {
  var builder: PrototypePattern.Builder = new PrototypePattern.Builder();
  var i = 0;
  for (i = 1; i <= 3; i += 1) {
    console.log(builder.createOne("c" + i).toString());
  }
}

언제 사용할까 ?

상속 기반으로 구조를 짜지 않아도 될때 사용한다. 상속되는 메서드의 구조가 복잡해 질때 사용해서 의존 관계를 끊을 수 있다.생성된 객체는 인스턴스가 아니기 때문에 맘대로 사용가능

장점

  • 싱속 구조를 고려 하지 않아도 된다.
  • 객체의 생성쪽을 캡슐화 할수 있다. 또한 생략할수도 있다. 클론 메서드로

단점

  • clone() 메소드 에서 순환 참조가 많은 경우 복제가 힘들 수 있다.
  • 초기화 로직을 구현하기 어렵다.