Observer
Observer
Section titled “Observer”パターン一言説明
Section titled “パターン一言説明”発行者の状態変化が購読者へ自動通知されるようにするリアクティブパターンです。
Unity でよく使う状況
Section titled “Unity でよく使う状況”- 体力変化に UI、サウンド、実績を同時に反応させたいとき
- 疎結合なイベント接続が必要なとき
構成要素(役割)
Section titled “構成要素(役割)”- Subject
- Observer
- Subscribe / Unsubscribe
Unity 例 (C#)
Section titled “Unity 例 (C#)”以下のコードは、上で説明した状況を Unity プロジェクトの文脈で単純化した例です。
using System;
public sealed class HealthModel{ public event Action<int, int> HealthChanged;
public void SetHealth(int currentHealth, int maxHealth) { HealthChanged?.Invoke(currentHealth, maxHealth); }}
public sealed class HealthBarPresenter{ public void Bind(HealthModel healthModel) { healthModel.HealthChanged += OnHealthChanged; }
private void OnHealthChanged(int currentHealth, int maxHealth) { }}- 振る舞いを分離できるため、変更の影響範囲を小さくできます。
- ルールの追加や差し替えを比較的安全に行えます。
- オブジェクト数や間接呼び出しが増えると、流れを追いにくくなります。
- 実行順序のバグはテストで固定しておく必要があります。
動作ダイアグラム
Section titled “動作ダイアグラム”主体の状態変化が購読者へ自動的に伝播する流れです。