オブザーバー パターン デリゲート プロトタイプ:
デリゲートで、辞書を使用してリスナーを追加または削除します
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 观察者模式
/// </summary>
public class EventDispather : Singleton<EventDispather>
{
//委托原型
public delegate void OnActionHandler(params object[] parmas);
//委托字典
private Dictionary<int,List<OnActionHandler>> dic = new Dictionary<int, List<OnActionHandler>>();
/// <summary>
/// 添加监听
/// </summary>
/// <param name="id"></param>
/// <param name="handler"></param>
public void AddEventListenner(int id, OnActionHandler handler)
{
if (dic.ContainsKey(id))
{
dic[id].Add(handler);
}
else
{
List<OnActionHandler> ishandle = new List<OnActionHandler> ();
ishandle.Add(handler);
dic[id] = ishandle;
}
}
/// <summary>
/// 移除监听
/// </summary>
/// <param name="id"></param>
/// <param name="handler"></param>
public void RemoveEventListenner(int id, OnActionHandler handler)
{
if(dic.ContainsKey(id))
{
List<OnActionHandler > ishandle = dic[id];
ishandle.Remove(handler);
if(ishandle.Count == 0)
{
dic.Remove(id);
}
}
}
/// <summary>
/// 派发消息
/// </summary>
/// <param name="id"></param>
/// <param name="value"></param>
public void DisPath(int id, params object[] parmas)
{
if(dic.ContainsKey(id) )
{
List<OnActionHandler> ishandler = dic[id];
if(ishandler.Count > 0 && ishandler != null)
{
for (int i = 0; i < ishandler.Count; i++)
{
if (ishandler[i] != null)
{
ishandler[i](parmas);
}
}
}
}
}
}
送信されたメッセージ:
/// <summary>
/// 消息发送者
/// </summary>
public class EventSend : MonoBehaviour
{
// Update is called once per frame
void Update()
{
if (Input.GetKeyUp(KeyCode.A))
{
EventDispather.instance.DisPath(0, 9);
}
else if (Input.GetKeyUp(KeyCode.B))
{
EventDispather.instance.DisPath(1, 18);
}
}
}
オブザーバーは次のことを聞きます。
観察者A:
/// <summary>
/// 消息监听A,监听2个消息
/// </summary>
public class EventGetA : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
EventDispather.instance.AddEventListenner(0, Masege0);
EventDispather.instance.AddEventListenner(1, Masege1);
}
private void Masege1(object[] parmas)
{
Debug.Log((int)parmas[0] + "点下班");
}
private void Masege0(object[] parmas)
{
Debug.Log((int)parmas[0] + "点上班");
}
private void OnDestroy()
{
EventDispather.instance.RemoveEventListenner(0, Masege0);
EventDispather.instance.RemoveEventListenner(1, Masege1);
}
}
観察者B:
/// <summary>
/// 消息监听B,只监听其中一个消息
/// </summary>
public class EventGetB : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
EventDispather.instance.AddEventListenner(1, Masege1);
}
private void Masege1(object[] parmas)
{
Debug.Log((int)parmas[0] + "点下班");
}
private void OnDestroy()
{
EventDispather.instance.RemoveEventListenner(1, Masege1);
}
}
アドバンテージ:
- オブザーバー パターンにより、通常のデリゲートによる不必要なメッセージの受け入れを回避できます。
- ターゲットと観察者の間のカップリング関係が減少し、両者の間には抽象的なカップリング関係が存在します。依存関係逆転の原則に準拠します。
- トリガーメカニズムがターゲットとオブザーバーの間に確立されます。
欠点:
- ターゲットとオブザーバー間の依存関係が完全に解決されておらず、循環参照が発生する可能性があります。
・オブザーバオブジェクトが多い場合、通知の解除に時間がかかり、プログラムの効率に影響します。