using System;
using System.Collections.Generic;
using System.Text;
namespace 消息框架
{
public delegate void CallBack();
public delegate void CallBack<T>(T t);
public delegate void CallBack<T, U>(T t, U u);
public class MessageManager
{
static MessageManager m_instance = null;
static public MessageManager Instance
{
get
{
if (m_instance == null) m_instance = new MessageManager();
return m_instance;
}
}
const uint maxPriority = 15;
const int leftOff = 24;
Dictionary<uint, Delegate> eventTable = new Dictionary<uint, Delegate>();
public void AddListener(uint msgId, CallBack handle, uint priority = 8)
{
uint eventId = msgId | (priority << leftOff);
if (!eventTable.ContainsKey(eventId))
eventTable.Add(eventId, handle);
}
public void Broadcast(uint msgId)
{
for (uint i = 0; i < maxPriority; i++)
{
uint eventId = msgId | (i << leftOff);
Delegate d;
if (eventTable.TryGetValue(eventId, out d))
{
CallBack callBack = d as CallBack;
if (callBack != null)
callBack();
}
}
}
public void AddListener<T>(uint msgId, CallBack<T> handle, uint priority = 8)
{
uint eventId = msgId | (priority << leftOff);
if (!eventTable.ContainsKey(eventId))
eventTable.Add(eventId, handle);
}
public void Broadcast<T>(uint msgId, T t)
{
for (uint i = 0; i < maxPriority; i++)
{
uint eventId = msgId | (i << leftOff);
Delegate d;
if (eventTable.TryGetValue(eventId, out d))
{
CallBack<T> callBack = d as CallBack<T>;
if (callBack != null)
callBack(t);
}
}
}
public void AddListener<T, U>(uint msgId, CallBack<T, U> handle, uint priority = 8)
{
uint eventId = msgId | (priority << leftOff);
if (!eventTable.ContainsKey(eventId))
eventTable.Add(eventId, handle);
}
public void Broadcast<T, U>(uint msgId, T t,U u)
{
for (uint i = 0; i < maxPriority; i++)
{
uint eventId = msgId | (i << leftOff);
Delegate d;
if (eventTable.TryGetValue(eventId, out d))
{
CallBack<T, U> callBack = d as CallBack<T, U>;
if (callBack != null)
callBack(t, u);
}
}
}
}
} 使用如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace 消息框架
{
class Program
{
const uint Msg_Add = 1;
const uint Msg_Remove = 2;
static void Main(string[] args)
{
OnListener();
int id = 110;
string msg = "成功!";
MessageManager.Instance.Broadcast<int>(Msg_Add, id);
MessageManager.Instance.Broadcast(Msg_Remove, id, msg);
Console.ReadKey();
}
static void OnListener()
{
MessageManager.Instance.AddListener<int>(Msg_Add, Add);
MessageManager.Instance.AddListener<int,string>(Msg_Remove, Remove);
}
static void Add(int id)
{
Console.WriteLine(string.Format("添加Id{0}", id));
}
static void Remove(int id, string msg)
{
Console.WriteLine(string.Format("移除Id{0},结果:{1}", id, msg));
}
}
}开发和维护的过程中,我们都应该尽量避免深耦合的问题。上面这个简单的框架可以只是提供一个解耦的思路,欢迎拍砖。