/*
* 日期:2017年7月4日
* 功能说明:消息中心,添加侦听,移除侦听,消息分发
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BOFramework
{
///
/// 消息类,所有侦听消息和发送消息的参数,均以此为类型
/// 缺点:只能以此为参数类型,需要从object类型转到响应类型
///
public class EventMessage
{
public GameObject Sender;
public object Param;
public EventMessage(GameObject _sender, object _param)
{
this.Sender = _sender;
this.Param = _param;
}
public EventMessage(object _param)
{
this.Sender = null;
this.Param = _param;
}
public override string ToString()
{
return string.Format("sender={0},param={1}", this.Sender, this.Param);
}
}
public delegate void EventDelegate(EventMessage msg);
public class EventCenter
{
private static Dictionary
DicEventData = new Dictionary
();
private static Dictionary
DicEventDatas = new Dictionary
();
public static void OnListenerAdding(string _msgKey,Delegate _del)
{
if (!DicEventDatas.ContainsKey(_msgKey))
{
DicEventDatas.Add(_msgKey,null);
}
DicEventDatas[_msgKey] = _del;
}
///
/// 添加监听事件 ///
///
///
public static void AddListener(string _msgKey, EventDelegate _event)
{
if(!DicEventData.ContainsKey(_msgKey))
{
DicEventData.Add(_msgKey, null);
}
DicEventData[_msgKey] += _event;
}
///
/// 移除指定监听 ///
///
public static void RemoveListener(string _msgKey)
{
if (!DicEventData.ContainsKey(_msgKey))
{
DicEventData[_msgKey] = null;
DicEventData.Remove(_msgKey);
}
}
///
/// 移除所有监听 ///
public static void RemoveAllListener()
{
DicEventData.Clear();
}
public static void BroadCastMessage(string _msgKey)
{
BroadCastMessage(_msgKey,null);
}
///
/// 广播消息,带参数 ///
///
///
public static void BroadCastMessage(string _msgKey, EventMessage _msg)
{
EventDelegate _eDeleg;
if (DicEventData.TryGetValue(_msgKey, out _eDeleg))
{
_eDeleg(_msg);
}
}
}
}
简易消息管理器EventCenter
最新推荐文章于 2023-06-28 19:10:03 发布