Unity_內部消息機制

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using GameType;

public class Messenger{

    private static Dictionary<ClickType, Delegate> mDict = new Dictionary<ClickType, Delegate>();

    private static bool OnAddListener(ClickType type,Delegate handler)
    {
        if (!mDict.ContainsKey(type))
        {
            mDict.Add(type, null);
        }
        Delegate d = mDict[type];
        if (d != null && d.GetType()!=handler.GetType())
        {
            return false;
        }
        return true;
    }

    private static bool OnRemoveListener(ClickType type,Delegate handler)
    {
        if (mDict.ContainsKey(type))
        {
            Delegate d = mDict[type];
            if (d==null)
            {
                return false;
            }
            else if (d.GetType()!=handler.GetType())
            {
                return false;
            }
        }
        else
        {
            return false;
        }
        return true;
    }

    public static void AddListener(ClickType type,Callback handler)
    {
        if (!OnAddListener(type,handler))
        {
            return;
        }
        mDict[type] = (Callback)mDict[type] + handler;
    }

    public static void AddListener<T>(ClickType type,Callback<T> handler)
    {
        if (!OnAddListener(type,handler))
        {
            return;
        }
        mDict[type] = (Callback<T>)mDict[type] + handler;
    }

    public static void RemoveListener(ClickType type,Callback handler)
    {
        if (!OnRemoveListener(type,handler))
        {
            return;
        }
        mDict[type] = (Callback)mDict[type] - handler;
        if (mDict[type]==null)
        {
            mDict.Remove(type);
        }
    }

    public static void RemoveListener<T>(ClickType type,Callback<T> handler)
    {
        if (!OnRemoveListener(type, handler))
        {
            return;
        }
        mDict[type] = (Callback<T>)mDict[type] - handler;
        if (mDict[type] == null)
        {
            mDict.Remove(type);
        }
    }

    public static void Broadcast(ClickType type)
    {
        if (!mDict.ContainsKey(type))
        {
            return;
        }
        Delegate d;
        if(mDict.TryGetValue(type, out d))
        {
            Callback callback = d as Callback;
            if (callback != null)
                callback();
            else
                return;
        }
    }

    public static void Broadcast<T>(ClickType type,T arg)
    {
        if (!mDict.ContainsKey(type))
        {
            return;
        }
        Delegate d;
        if (mDict.TryGetValue(type, out d))
        {
            Callback<T> callback = d as Callback<T>;
            if (callback != null)
                callback(arg);
            else
                return;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章