[TWLFramework] MessageCenter

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

public class MessageCenter : Singleton<MessageCenter>
{

private Dictionary<string, List<MessageEvent>> _dictMessageEvent = null;
public override void Init()
{
_dictMessageEvent = new Dictionary<string, List<MessageEvent>>();
}
//add listener
public void AddListener(string msgName, MessageEvent msgEvent)
{
List<MessageEvent> list = null;
if (_dictMessageEvent.ContainsKey(msgName))
{
list = _dictMessageEvent[msgName];
}
else {
list = new List<MessageEvent>();
_dictMessageEvent.Add(msgName, list);
}
if (!list.Contains(msgEvent))
{
list.Add(msgEvent);
}
}
//remove listener
public void RemoveListener(string msgName, MessageEvent msgEvent)
{
if (_dictMessageEvent.ContainsKey(msgName))
{
List<MessageEvent> list = _dictMessageEvent[msgName];
if (list.Contains(msgEvent))
{
list.Remove(msgEvent);
}
if (list.Count <= 0)
{
_dictMessageEvent.Remove(msgName);
}
}
}
//remove all listener
public void RemoveAllListener()
{
_dictMessageEvent.Clear();
}
#region send message
public void SendMessage(Message message)
{
DoMessageDispatcher(message);
}

public void SendMessage(string name, object sender)
{
SendMessage(new Message(name, sender));
}
public void SendMessage(string name, object sender, object content)
{
SendMessage(new Message(name, sender, content));
}
public void SendMessage(string name, object sender, object content, params object[] dictParams)
{
SendMessage(new Message(name, sender, content, dictParams));
}
private void DoMessageDispatcher(Message msg)
{
if (_dictMessageEvent == null || !_dictMessageEvent.ContainsKey(msg.Name))
{
return;
}
List<MessageEvent> list = _dictMessageEvent[msg.Name];
for (int i = 0; i < list.Count; i++)
{
MessageEvent msgEvent = list[i];
if (msgEvent != null)
{
msgEvent(msg);
}
}

}

 

#endregion

 


}

posted on 2016-08-18 19:58  tianjiuwan  阅读(248)  评论(0编辑  收藏  举报