自定义的事件管理器

            自定义的事件管理器

              周银辉

 

大多数框架下都提供了事件管理器的,但不使用框架时为了让事件发送者和事件接收者之间解耦,就可以如下写个简单的

    public enum EventAdministratorEventTypes
    {
        ApplicationStartup, //在这里添加你需要的事件
    }

    public class EventAdministratorEventArgs : EventArgs
    {
        public object Arg
        {
            get;
            protected set;
        }

        public EventAdministratorEventArgs(object arg)
        {
            Arg = arg;
        }
    }


    public class EventAdministrator
    {
        private static EventAdministrator instance;

        public static EventAdministrator Instance
        {
            get { return instance ?? (instance = new EventAdministrator()); }
        }

        /// <summary>
        /// 用于存储event和它对于的回调函数列表的字典(event 和 callback是一对多的关系)
        /// </summary>
        private readonly Dictionary<EventAdministratorEventTypes, List<EventHandler<EventAdministratorEventArgs>>> 
            eventAndCallbackBuffer = 
            new Dictionary<EventAdministratorEventTypes, List<EventHandler<EventAdministratorEventArgs>>>();


        private void AddCallbackForEvent(EventAdministratorEventTypes eventName,
            EventHandler<EventAdministratorEventArgs> callback)
        {
            if (!eventAndCallbackBuffer.ContainsKey(eventName))
            {
                eventAndCallbackBuffer.Add(eventName, new List<EventHandler<EventAdministratorEventArgs>>());
            }

            var callbackList = eventAndCallbackBuffer[eventName];
            //添加时判定不存在为了防止多次注册后引起多次调用回调函数
            if (!callbackList.Contains(callback))
            {
                callbackList.Add(callback);
            }
        }

        /// <summary>
        /// 注册为事件接受者
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <param name="callback">事件发生时的回调函数</param>
        public void Register(EventAdministratorEventTypes eventName, EventHandler<EventAdministratorEventArgs> callback)
        {
            AddCallbackForEvent(eventName, callback);

        }

        /// <summary>
        /// 触发一个事件
        /// </summary>
        /// <param name="sender">触发者</param>
        /// <param name="eventName">事件名称</param>
        /// <param name="args">触发该事件时所带的参数</param>
        public void Send(object sender, EventAdministratorEventTypes eventName, EventAdministratorEventArgs args)
        {
            if (!eventAndCallbackBuffer.ContainsKey(eventName))
            {
                Logger.Warning("EventAdministrator:事件"+eventName+"被触发,但没有任何对象注册该事件." +
                               " 导致这个情况的原因可能有:代码中没有调用相应的Register函数来注册该事件; 或者 事件的Send函数发生在Register之前");
                return;
            }

            var callbackList = eventAndCallbackBuffer[eventName];

            foreach (var callback in callbackList)
            {
                callback.Invoke(sender, args);
            }
        }
    }
}

 

 

posted @ 2014-06-20 10:52  周银辉  阅读(2292)  评论(2编辑  收藏  举报