简单的观察者模式

public enum Game
{
    START,
    END
}
public class GuanChaZheBase
{
    private static GuanChaZheBase instance;
    public static GuanChaZheBase Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new GuanChaZheBase();
            }
            return instance;
        }
    }

    public Dictionary<Game, Action> m_EventTable = new Dictionary<Game, Action>();
    /// <summary>
    /// 添加事件
    /// </summary>
    /// <param name="Type"></param>
    /// <param name="callBack"></param>
    public void AddListence(Game Type, Action callBack)
    {
        if (!m_EventTable.ContainsKey(Type))
        {
            m_EventTable.Add(Type, null);
        }
        if (m_EventTable[Type] != null && m_EventTable[Type].GetType() != callBack.GetType())
        {
            Debug.LogError("添加的事件:" + callBack.GetType() + "与原有事件:" + m_EventTable[Type].GetType() + "冲突");
        }
        m_EventTable[Type] = m_EventTable[Type] + callBack;
    }

    public void RemoveListence(Game Type, Action callBack)
    {
        if (!m_EventTable.ContainsKey(Type))
        {
            Debug.LogError("没有事件码为:" + Type + "的事件");
        }
        else
        {
            if (m_EventTable[Type] == null)
            {
                Debug.LogError("当前事件为空");
            }
            if (m_EventTable[Type].GetType() != callBack.GetType())
            {
                Debug.LogError("要移除事件与原有事件类型不同");
            }
        }
        m_EventTable[Type] = m_EventTable[Type] - callBack;
        if (m_EventTable[Type] == null)
        {
            m_EventTable.Remove(Type);
        }
    }
    public void Brodcast(Game type)
    {
        Action d;
        if (m_EventTable.TryGetValue(type, out d))
        {
            Action callback = d;
            if (callback != null)
            {
                callback();
            }   
            else
            {
                Debug.LogError("广播事件错误");
            }
        }
    }
}

观察者模式的使用

public class GameManager : MonoBehaviour
{

    // Start is called before the first frame update
    void Start()
    {
 
    }

    private void OnEnable()
    {
        GuanChaZheBase.Instance.AddListence(Game.START, StartPanel);
        GuanChaZheBase.Instance.Brodcast(Game.START);
    }
    
    public void StartPanel()
    {
        GameObject go = Instantiate(Resources.Load("StartPanel") as GameObject, FindObjectOfType<Canvas>().transform);
    }

使用完以后一定要在OnDestroy或者OnDisable中移除事件

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值