# 플라이웨이트 패턴

---

플라이웨이트 패턴은 유사한 여러 개체 간에 가능한 한 많은 데이터를 공유하여 메모리 사용을 최소화하고 성능을 향상시키는 것을 목표로 하는 디자인 패턴이다. 이 패턴에서는 내부적으로 풀을 관리하고, 풀에 없는 경우에만 새 플라이웨이트 개체를 만들고 그렇지 않으면 기존 인스턴스를 반환한다.

주로 동일한 속성을 가진 많은 작은 개체가 생성되는 게임 등에서 많이 사용된다. 롤을 예로 들어보자.

```
// Flyweight class
class Champion {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }
  
  display() {
    console.log(`Displaying ${this.name}, the ${this.role}`);
    console.log(`Image: ${this.image}`);
  }
}

// Flyweight factory
class ChampionFactory {
  constructor() {
    this.pool = {};
  }
  
  getChampion(name) {
    if (!this.pool[name]) {
      let role;
      if (name === 'Ashe') {
        role = '원딜';
      } else if (name === 'Lux') {
        role = '미드';
      } else if (name === 'Garen') {
        role = '탑';
      } else {
        throw new Error(`Invalid champion name: ${name}`);
      }
      this.pool[name] = new Champion(name, role);
    }
    return this.pool[name];
  }
}

// Client class
class LeagueOfLegends {
  constructor() {
    this.factory = new ChampionFactory();
    this.champions = [];
  }
  
  selectChampion(name) {
    const champion = this.factory.getChampion(name);
    champion.display();
    this.champions.push(champion);
  }
}

// Usage example
const game = new LeagueOfLegends();
game.selectChampion('Ashe');
game.selectChampion('Lux');
game.selectChampion('Garen');
game.selectChampion('Ashe');
```

[https://slashpage.com/e/develop/7xjqy1g2vvp926vd54zk](https://slashpage.com/e/develop/7xjqy1g2vvp926vd54zk)

[https://slashpage.com/e/develop/7xjqy1g2vvp926vd54zk](https://slashpage.com/e/develop/7xjqy1g2vvp926vd54zk)

For the site tree, see the [root Markdown](https://slashpage.com/develop.md).
