[typescript] 플라이웨이트 패턴과 타입스크립트의 결합 사례

플라이웨이트 패턴은 객체를 효율적으로 공유하여 메모리 사용량을 최적화하는 디자인 패턴입니다. 타입스크립트를 사용하여 이 패턴을 구현하는 방법은 매우 효율적일 수 있습니다.

플라이웨이트 패턴

플라이웨이트 패턴은 중복된 객체를 최대한 피하고, 객체를 공유하여 메모리를 절약하는 것을 목표로 합니다. 특히 상태 공유가 가능하고, 불변한 객체들에 적합합니다. 예를 들어 게임 엔진에서 유사한 캐릭터나 오브젝트를 관리할 때 사용될 수 있습니다.

타입스크립트에서의 플라이웨이트 패턴 구현

타입스크립트는 강력한 타입 시스템을 제공하므로 플라이웨이트를 쉽게 구현할 수 있습니다. 인터페이스나 클래스를 이용하여 객체를 정의하고, private 멤버나 읽기 전용 속성을 사용하여 객체를 불변하게 만들 수 있습니다.

다음은 타입스크립트를 사용한 플라이웨이트 패턴의 간단한 예제입니다:

interface Flyweight {
  operation(extrinsicState: number): void;
}

class ConcreteFlyweight implements Flyweight {
  private intrinsicState: number;

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

  operation(extrinsicState: number): void {
    console.log(`Intrinsic state: ${this.intrinsicState}, Extrinsic state: ${extrinsicState}`);
  }
}

class FlyweightFactory {
  private flyweights: { [key: string]: Flyweight } = {};

  getFlyweight(key: string): Flyweight {
    if (!(key in this.flyweights)) {
      this.flyweights[key] = new ConcreteFlyweight(parseInt(key, 10));
    }
    return this.flyweights[key];
  }
}

const factory = new FlyweightFactory();
const flyweight1 = factory.getFlyweight('1');
const flyweight2 = factory.getFlyweight('2');
flyweight1.operation(10);
flyweight2.operation(20);

위의 예제에서 ConcreteFlyweight 클래스가 플라이웨이트를 구현하고, FlyweightFactory 클래스가 플라이웨이트 객체를 관리합니다.

결론

플라이웨이트 패턴은 메모리 사용량을 최적화하는 데 도움이 되는 디자인 패턴이며, 타입스크립트를 사용하면 객체지향적으로 이 패턴을 쉽게 구현할 수 있습니다. 특히 타입 시스템을 이용하여 객체 상태를 관리하고 불변성을 유지할 수 있습니다.

참고 자료