メインコンテンツまでスキップ

🧩 Flyweight パターン

✅ 設計意図

  • 同じデータやロジックを持つオブジェクトを共有して、必要な情報だけ外部化して保持する
  • 大量の似たようなインスタンスを最小限の構造で扱う

✅ 適用理由

  • UI 構成、ステータス表示、ラベル、ボタンなど、表示内容が異なるだけの処理を共通化
  • 一部だけ違う処理を、共通処理+可変要素で構成可能に

✅ 向いているシーン

  • 大量の UI パーツ、テキストオブジェクト、座席データなど
  • メモリ削減、構造の簡素化をしたい場面

✅ コード例

// Flyweight(共通部分)
class NotificationTemplate {
constructor(public header: string, public footer: string) {}

format(user: string, body: string): string {
return `${this.header}\n宛先: ${user}\n本文: ${body}\n${this.footer}`;
}
}

// Context(可変部分を持つ)
class Notification {
constructor(
private user: string,
private message: string,
private template: NotificationTemplate
) {}

send() {
console.log(this.template.format(this.user, this.message));
}
}

// 利用例:テンプレートは共有
const sharedTemplate = new NotificationTemplate(
"件名: お知らせ",
"-- 通知システム"
);

new Notification("hiroshi", "メッセージ1", sharedTemplate).send();
new Notification("satoshi", "メッセージ2", sharedTemplate).send();

✅ 解説

このコードは Flyweight パターン を使用して、NotificationTemplate を共有し、メモリ使用量を削減する設計を実現している。 Flyweight パターンは、オブジェクトの共有を通じてメモリ使用量を最適化するデザインパターン。 共通部分(NotificationTemplate)を共有し、可変部分(Notification)を個別に管理することで効率的なリソース利用を実現している。

1. Flyweight パターンの概要

  • Flyweight: 共有される不変部分を表現するクラス
    • このコードでは NotificationTemplate が該当
  • Context: 可変部分を持ち、Flyweight を利用するクラス
    • このコードでは Notification が該当
  • Client: Flyweight を利用してオブジェクトを生成するコード
    • このコードでは sharedTemplate を共有して Notification を生成する部分が該当

2. 主なクラスとその役割

  • NotificationTemplate
    • Flyweight クラス
    • 通知のヘッダーやフッターなどの共通部分を保持
    • format メソッドで、ユーザーや本文を含む完全な通知メッセージを生成
  • Notification
    • Context クラス
    • ユーザーやメッセージといった可変部分を保持
    • FlyweightNotificationTemplate)を利用して通知を送信
  • クライアントコード
    • NotificationTemplate を共有し、複数の Notification インスタンスを生成

3. UML クラス図

4. Flyweight パターンの利点

  • メモリ使用量の削減: 共通部分(NotificationTemplate)を共有することで、メモリ使用量を最適化
  • 効率的なリソース利用: 不変部分と可変部分を分離することで、効率的なリソース管理が可能
  • 拡張性: 新しい可変部分を追加する場合も、Flyweight を再利用できる

この設計は、共通部分を複数のオブジェクトで共有する必要がある場面で非常に有効であり、メモリ効率を向上させる。