플라이웨이트 패턴

객체를 최대한 공유해서 메모리를 절약하는 패턴

  • 비슷한 객체가 많이 생성될 때 공통되는 부분은 공유하고, 개별적인 값만 외부에서 주입해서 사용하는 방식

  • 해시맵을 통해 키가 겹치지 않는 객체들을 저장하고 찾는 객체가 해시맵에 저장여부에 따라 새로 생성 및 재사용됨

  • 무엇을 키로 삼을지가 핵심


1. 플라이웨이트 구현체

// Flyweight interface
interface Font {
  apply(text: string): void
}

class ConcreteFont implements Font {
  constructor(public font: string, public size: number, public color: string) {}
  
  apply(text: string) {
    console.log(`Text: ${text} with Font: ${this.font},
       Size: ${this.size}, Color: ${this.color}`)
  }
}

2. 팩토리 클래스

3. 클라이언트 코드

Last updated