简单的事件系统:可以通过操作码来执行相关的函数操作,还可以通过分模块,再添加一个模块码,进一步细分事件系统
using System.Collections.Generic;
using System;
/// <summary>
/// 简单的事件系统
/// </summary>
public class EventMgr
{
private static EventMgr m_instance;
public static EventMgr Instance
{
get
{
if (m_instance == null)
{
m_instance = new EventMgr();
}
return m_instance;
}
}
private EventMgr() { }
private Dictionary<CMD, List<System.Action<object[]>>> map = new Dictionary<CMD, List<Action<object[]>>>();
public void Add(CMD key, Action<object[]> func)
{
if (!map.ContainsKey(key))
{
List<System.Action<object[]>> list = new List<Action<object[]>>();
map.Add(key, list);
}
map[key].Add(func);
}
public void Remove(CMD key, Action<object[]> func)
{
if (map.ContainsKey(key))
{
if (map[key].Contains(func))
{
map[key].Remove(func);
if (map[key].Count == 0)
{
map[key].Clear();
map.Remove(key);
}
}
}
}
/// <summary>
/// 触发消息
/// </summary>
/// <param name="key">事件码</param>
/// <param name="data">参数</param>
public void Trigger(CMD key, params object[] data)
{
if (map.ContainsKey(key))
{
int l = map[key].Count;
for (int i = 0; i < l; i++)
{
map[key][i](data);
}
}
}
}
public enum CMD
{
Add_Equip,
Remove_Equip
}