张德长

导航

设计模式-观察者模式Observe的实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 观察者模式
/// by:zdz
/// date:20220328
/// </summary>
public class Dispatcher : Singleton<Dispatcher>
{
    public delegate void ActionHandler(params object[] param);
    private Dictionary<int, ActionHandler> handlerDictionary = new Dictionary<int, ActionHandler>();
    /// <summary>
    /// 增加监听
    /// </summary>
    /// <param name="id"></param>
    /// <param name="handler"></param>
    public void AddListener(int id, ActionHandler handler)
    {
        if (handlerDictionary.ContainsKey(id))
        {
            handlerDictionary[id] += handler;
        }
        else
        {
            handlerDictionary.Add(id, handler);
        }
    }
    /// <summary>
    /// 移除监听
    /// </summary>
    /// <param name="id"></param>
    /// <param name="handler"></param>
    public void RemoveListener(int id, ActionHandler handler)
    {
        if (handlerDictionary.ContainsKey(id))
        {
            if (handlerDictionary[id] != null)
            {
                handlerDictionary[id] -= handler;
            }
            else
            {
                handlerDictionary.Remove(id);
            }
        }
    }
    /// <summary>
    /// 派发
    /// </summary>
    /// <param name="id"></param>
    /// <param name="param"></param>
    public void Dispatch(int id, params object[] param)
    {
        if (handlerDictionary.ContainsKey(id))
        {
            if (handlerDictionary[id] != null)
            {
                handlerDictionary[id](param);
            }
        }
    }
}

 

posted on 2022-03-29 16:03  张德长  阅读(39)  评论(0编辑  收藏  举报