需求:不同道具需要不同的处理,例如道具1可以释放钩子,道具2召唤狗子
对于这些不同的效果,如果直接继承重写使用函数,对于热更。后期维护是非常不友好的
事实上不同的道具其实是对不同数据的处理
我们只需要先编写数据类,然后对数据类处理就好
demo:
先编写数据类
public struct Move
{
public float from;
public float to;
}
然后对数据处理
public interface IEvent
{
void Handle();
void Handle(object a);
}
public abstract class AEvent : IEvent
{
void IEvent.Handle()
{
Run();
}
protected abstract void Run();
void IEvent.Handle(object a)
{
throw new NotImplementedException();
}
}
public abstract class AEvent<T> : IEvent where T : struct
{
void IEvent.Handle()
{
throw new NotImplementedException();
}
void IEvent.Handle(object a)
{
Run((T)a);
}
protected abstract void Run(T a);
}
public class Log2Event : AEvent<Move>
{
protected override void Run(Move a)
{
System.Console.WriteLine($"from:{a.from} to:{a.to}");
}
}
简单测试一下
class Program
{
static void Main(string[] args)
{
(new Log2Event() as IEvent).Handle(new Move {from=0,to=1 });
}
}
毫无疑问,重写处理函数和原有数据类一点关系也没有。
从上面很明显可以看出,处理函数生存周期应该是从从应用开始到应用关闭
所以我们只需要在初始化游戏的时候创建处理函数即可,假设要更新处理函数,直接替换就行
class Program
{
static void Main(string[] args)
{
Dictionary<Type, IEvent> dict = new Dictionary<Type, IEvent>();
dict.Add(typeof(Move), new Log2Event());
var move = new Move { from = 0,to=1 };
dict[move.GetType()].Handle(move);
}
}
乍一看上去好像没有问题。万一我们有100个数据类,难道要写100个Add?
这个时候就应该上反射,反射整个程序集,遍历处理函数添加到字典里面。
定义字典Key,啥类型都行,只要是唯一值就没问题
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class EventAttribute : Attribute
{
public string eventId;
public EventAttribute(string eventId)
{
this.eventId = eventId;
}
}
遍历程序集所有添加了key的处理函数,添加到字典中
public class EventSystem
{
readonly Dictionary<string, List<IEvent>> dict = new Dictionary<string, List<IEvent>>();
public EventSystem(System.Reflection.Assembly assembly)
{
var eventAttribute = typeof(EventAttribute);
foreach (var type in assembly.GetTypes())
{
if (type.IsAbstract||type.IsInterface)
continue;
var attr = type.GetCustomAttributes(eventAttribute, false);
if (attr.Length == 0)
continue;
var obj = Activator.CreateInstance(type) as IEvent;
if (obj == null)
continue;
var e = attr[0] as EventAttribute;
if (!dict.ContainsKey(e.eventId))
dict.Add(e.eventId, new List<IEvent>());
dict[e.eventId].Add(obj);
}
}
public void Run(string eventId)
{
List<IEvent> list;
if (!dict.TryGetValue(eventId, out list))
return;
foreach (var e in list)
{
try
{
e.Handle();
}
catch (Exception ex)
{
throw ex;
}
}
}
public void Run<T>(string eventId,T a)where T : struct
{
List<IEvent> list;
if(!dict.TryGetValue(eventId, out list))
return;
foreach (var e in list)
{
try
{
e.Handle(a);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
使用示例:
[Event("test")]
public class LogEvent : AEvent
{
protected override void Run()
{
System.Console.WriteLine("test");
}
}
class Program
{
static void Main(string[] args)
{
var eventSystem = new EventSystem(typeof(Program).Assembly);
eventSystem.Run("test");
eventSystem.Run("test2", new Move { from = 0, to = 1 });
}
}