ちゃんなるぶろぐ

エンジニア5年生🧑‍💻 オライリーとにらめっこする毎日。

【5分でわかる📚】TypeScriptでDesign Pattern〜Flyweight Pattern〜

どうも、ちゃんなるです!

今回は、Flyweight Patternを紹介します🖐️

概要

Flyweight Patternは、多数の類似オブジェクトを扱う際に、メモリ消費を抑える効果があります。

今回示すプログラムの設計

シナリオとして、図書館の本の情報管理システムを考えます📚

各本は、タイトル、著者、ジャンルなどの情報を持っていますが、ジャンルは限られた数しか存在しません。

Flyweight Patternを使って、メモリ効率を向上させましょう。

クラス図

サンプルコードのクラス図:Mermaid Live Editorで作成

クラス名 役割
Book 本の情報を表すクラス
GenreFlyweightFactory ジャンルを生成・管理するファクトリクラス
GenreFlyweight ジャンルオブジェクトを共有するためのインターフェース
Genre 具体的なジャンルを表すクラス

サンプルコード

interface GenreFlyweight {
  getGenre(): string;
}
class Genre implements GenreFlyweight {
  constructor(private genre: string) {}

  getGenre(): string {
    return this.genre;
  }
}
class GenreFlyweightFactory {
  private genres: { [key: string]: Genre } = {};

  getGenre(name: string): Genre {
    if (!this.genres[name]) {
      this.genres[name] = new Genre(name);
    }
    return this.genres[name];
  }
}
class Book {
  constructor(private title: string, private author: string, private genre: GenreFlyweight) {}

  getDetails(): string {
    return `${this.title} by ${this.author}, Genre: ${this.genre.getGenre()}`;
  }
}

では、実際に使ってみましょう🖐️

const factory = new GenreFlyweightFactory();
const thriller = factory.getGenre("Thriller");
const sciFi = factory.getGenre("Sci-Fi");

const thriller2 = factory.getGenre("Thriller");
console.log(thriller === thriller2); // true -> 同じインスタンスが参照されている👍

const book1 = new Book("The Da Vinci Code", "Dan Brown", thriller);
console.log(book1.getDetails());

const book2 = new Book("Angels & Demons", "Dan Brown", thriller);
console.log(book2.getDetails());

const book3 = new Book("Dune", "Frank Herbert", sciFi);
console.log(book3.getDetails());

Flyweight Patternの使い道

  • 類似オブジェクトの多いシステム
  • 大量のデータを効率的に管理したい場合
  • オブジェクトの共有が適切である場合

組み合わせられるデザインパターン

  • Singleton Pattern: Flyweight Patternと共にSingleton Patternを使用することで、ファクトリクラスを一意のインスタンスとして扱い、状態の共有や一貫性を保つことができます。

chan-naru.hatenablog.com

  • Composite Pattern: Flyweight PatternとComposite Patternを組み合わせることで、複雑なオブジェクト階層を持つシステムでも効率的なリソース管理が実現できます。

chan-naru.hatenablog.com

  • Factory Method Pattern: Flyweight PatternとFactory Method Patternを組み合わせることで、オブジェクト生成の詳細を隠蔽し、柔軟かつメモリ効率の高いオブジェクト生成が可能になります。

chan-naru.hatenablog.com

まとめ

Flyweight Patternは、多数の類似オブジェクトを効率的に管理するためのデザインパターンです。

このパターンは、メモリ使用量を削減することで、アプリケーションのパフォーマンスを向上させることができます。

今回の図書館の例では、ジャンルを表すオブジェクトを共有することで、メモリ使用量を抑えました。

このように、Flyweight Patternを適切に活用することで、システムの効率を大幅に向上させることが可能です👍

参考文献

www.oreilly.com

en.wikipedia.org