C#单例模式,多线程安全
//Singleton.cs
public class Singleton<T> where T : new()
{
private static T _instance;
private static object _lock = new object();
protected Singleton() {}
public static T Instance()
{
if(_instance == null)
{
lock(_lock)
{
if(_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
C#消息分发机制,用了delegate
//MessageDispatcher.cs
using System.Collections;
using System.Collections.Generic;
public class MyMessageDispatcher : Singleton<MyMessageDispatcher>
{
Dictionary<uint, MessageHandler> m_HandlerMap;
public MyMessageDispatcher()
{
m_HandlerMap = new Dictionary<uint, MessageHandler> ();
}
public void RegisterMessageHandler(uint iMessageType, MessageHandler handler)
{
if (handler == null)
return;
if (!m_HandlerMap.ContainsKey (iMessageType))
{
MessageHandler Handlers = handler;
m_HandlerMap.Add (iMessageType, Handlers);
}
else
{
m_HandlerMap[iMessageType] += handler;
}
}
public void UnRegisterMessageHandler(uint iMessageType, MessageHandler handler)
{
if (handler == null)
return;
if(m_HandlerMap.ContainsKey (iMessageType))
{
m_HandlerMap[iMessageType] -= handler;
}
}
public void SendMessage(uint iMessageType, object arg)
{
if(m_HandlerMap.ContainsKey (iMessageType))
{
if(m_HandlerMap[iMessageType] != null)
{
m_HandlerMap[iMessageType].Invoke(iMessageType, arg);
}
}
}
}
//EMessageType.cs中定义事件类型
public enum EUIMessage : uint
{
UITest0 = 0,
UITest1 = 1,
UITest2 = 2
}
使用消息分发机制示例:
//发出消息事件
MessageDispatcher.Instance().SendMessage((uint)EUIMessage.UITest0, “ouput”);
//接受消息端,先要注册侦听消息,此处的例子是在Unity3D中实现的
public class TestText : MonoBehaviour
{
void OnEnable()
{
MyMessageDispatcher.Instance ().RegisterMessageHandler ((uint)EUIMessage.UITest0, ChangePlay0);
}
void OnDisable()
{
MyMessageDispatcher.Instance ().UnRegisterMessageHandler ((uint)EUIMessage.UITest0, ChangePlay0);
}
public void ChangePlay0(uint iMessageType, object kParam)
{
string txt = (string) kParam;
GUIText text = GetComponent<GUIText>();
text.text = txt ;
}
}