起因
示例1 对象池:
1 2 3 4 5 6 7 8
| public class Wardrobe : BasicManager<Wardrobe> { private Dictionary<string, Drawers> objectPool = new Dictionary<string,Drawers>(); public class Drawers { private Queue<GameObject> drawer; public Queue<GameObject> Drawer { get { return drawer; } }
|
如果我要缓存的不只是GameObject的话,同时又要避免用Object导致的拆装箱,就想到了用泛型
1 2 3 4
| public class Drawers<T> { private Queue<T> drawer; public Queue<T> Drawer { get { return drawer; } }
|
但又出现了问题,成员泛型即需要泛型类,则对象池类也得是泛型类, 且缓存不同对象即需要多个对象池,显然不符合单例规则
示例2 观察者事件中心:
1 2 3
| public class EventCenter : BasicManager<EventCenter> { private Dictionary<string, UnityEvent> eventDic = new Dictionary<string, UnityEvent>();
|
相似的问题,如果事件的委托函数需要传参,且不同事件的参数类型还不同(避免用Object导致的拆装箱),要怎么做?
解决办法
以示例2为例,可以这样做
将委托再向上包装一层,且继承一个父类/接口,在使用时再利用里氏转换原则脱去外衣
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| interface IEvent{} class EventYield<T> : IEvent { public UnityEvent<T> action; } class EventYield : IEvent { public UnityEvent action; } public class EventCenter : BasicManager<EventCenter> { private Dictionary<string, IEvent> eventDic = new Dictionary<string, IEvent>(); } 获取有参委托函数时 eventDic[name] as EventYield<T>.action 获取无参委托函数时 eventDic[name] as EventYield.action 再配合函数重载,这样就可以实现需求了
|