C#单例模式,多线程安全
1//Singleton.cs 2public class Singleton<T> where T : new() 3{ 4 private static T _instance; 5 private static object _lock = new object(); 6 7 protected Singleton() {} 8 public static T Instance() 9 { 10 if(_instance == null) 11 { 12 lock(_lock) 13 { 14 if(_instance == null) 15 { 16 _instance = new T(); 17 } 18 } 19 } 20 return _instance; 21 } 22}
C#消息分发机制,用了delegate
1//MessageDispatcher.cs 2using System.Collections; 3using System.Collections.Generic; 4public class MyMessageDispatcher : Singleton<MyMessageDispatcher> 5{ 6 Dictionary<uint, MessageHandler> m_HandlerMap; 7 8 public MyMessageDispatcher() 9 { 10 m_HandlerMap = new Dictionary<uint, MessageHandler> (); 11 } 12 13 public void RegisterMessageHandler(uint iMessageType, MessageHandler handler) 14 { 15 if (handler == null) 16 return; 17 18 19 if (!m_HandlerMap.ContainsKey (iMessageType)) 20 { 21 MessageHandler Handlers = handler; 22 m_HandlerMap.Add (iMessageType, Handlers); 23 } 24 else 25 { 26 m_HandlerMap[iMessageType] += handler; 27 } 28 } 29 30 public void UnRegisterMessageHandler(uint iMessageType, MessageHandler handler) 31 { 32 if (handler == null) 33 return; 34 35 if(m_HandlerMap.ContainsKey (iMessageType)) 36 { 37 m_HandlerMap[iMessageType] -= handler; 38 } 39 } 40 41 public void SendMessage(uint iMessageType, object arg) 42 { 43 if(m_HandlerMap.ContainsKey (iMessageType)) 44 { 45 if(m_HandlerMap[iMessageType] != null) 46 { 47 m_HandlerMap[iMessageType].Invoke(iMessageType, arg); 48 } 49 } 50 } 51} 52 53//EMessageType.cs中定义事件类型 54public enum EUIMessage : uint 55{ 56 UITest0 = 0, 57 UITest1 = 1, 58 UITest2 = 2 59}
使用消息分发机制示例:
1//发出消息事件 2MessageDispatcher.Instance().SendMessage((uint)EUIMessage.UITest0, “ouput”); 3 4//接受消息端,先要注册侦听消息,此处的例子是在Unity3D中实现的 5public class TestText : MonoBehaviour 6{ 7 void OnEnable() 8 { 9 MyMessageDispatcher.Instance ().RegisterMessageHandler ((uint)EUIMessage.UITest0, ChangePlay0); 10 } 11 12 void OnDisable() 13 { 14 MyMessageDispatcher.Instance ().UnRegisterMessageHandler ((uint)EUIMessage.UITest0, ChangePlay0); 15 } 16 17 public void ChangePlay0(uint iMessageType, object kParam) 18 { 19 string txt = (string) kParam; 20 GUIText text = GetComponent<GUIText>(); 21 text.text = txt ; 22 } 23}