[Unity] Utilities 之 MessageDispatcher
文章目录
参考资料:
- https://gpp.tkchu.me/event-queue.html
- Message Dispatcher插件
1.设计
Message
IMessage接口定义了消息的基本属性。
Message实现接口,并构建对象池,提供New、Free方法生成实例、释放实例。
public interface IMessage {
string Type {
get; set; }
string Recipient {
get; set; }
object Data {
get; set; }
float Delay {
get; set; }
object Sender {
get; set; }
bool IsSent {
get; set; }
bool IsHandled {
get; set; }
void Clear();
}
public class Message : IMessage {
public string Type {
get; set; }
public string Recipient {
get; set; }
public object Data {
get; set; }
public float Delay {
get; set; }
public object Sender {
get; set; }
public bool IsSent {
get; set; }
public bool IsHandled {
get; set; }
public void Clear () {
Type = "";
Recipient = null;
Data = null;
Delay = 0;
Sender = null;
IsSent = false;
IsHandled = false;
}
// msg pool
private static ObjectPool<Message> m_MsgPool = new ObjectPool<Message> (10, false);
public static Message New () {
Message instance = m_MsgPool.New ();
if (instance == null) {
Debug.LogError ("Can't create Msg Instance!"); }
instance.IsSent = false;
instance.IsHandled = false;
return instance;
}
public static void Free (Message instance) {
if (instance == null) return;
instance.IsSent = true;
instance.IsHandled = true;
m_MsgPool.Free(instance);
}
public static void Free(IMessage instance){
if(instance == null) return;
instance.Clear();
instance.IsSent = true;
instance.IsHandled = true;
if(instance is Message)
m_MsgPool.Free((Message)instance);
}
}
Listener
MessageListenerDefinition用于创建监听者实例。设计方式与Message相似。
public class MessageListenerDefinition {
/// <summary>
/// Msg Type
/// </summary>
/// <va