zoukankan      html  css  js  c++  java
  • 事件管理器

    项目开发过程中经常会用到代理事件,为方便管理,避免代码混乱,需要一个总的事件管理器:

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System;
    
    public class EventManager<T> {
        
        private static Dictionary<EventType,List<Action<T>>> eventDic = new Dictionary<EventType,List<Action<T>>>();
    
        /// <summary>
        /// 添加事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="act"></param>
        public static void AddEvent(EventType type, Action<T> act)
        {
            if (eventDic.ContainsKey(type))
            {
                if(!eventDic[type].Contains(act))
                {
                    eventDic[type].Add(act);
                }
            }else
            {
                List<Action<T>> list = new List<Action<T>>();
                eventDic.Add(type, list);
                list.Add(act);
            }
        }
    
        /// <summary>
        /// 移除事件
        /// </summary>
        /// <param name="type"></param>
        public static void RemoveEvent(EventType type)
        {
            if (eventDic.ContainsKey(type))
            {
                eventDic.Remove(type);
            }
        }
    
        public static void RemoveEvent(EventType type, Action<T> act)
        {
            if (eventDic.ContainsKey(type))
            {
                if (eventDic[type].Contains(act))
                {
                    eventDic[type].Remove(act);
                }
            }
        }
    
        /// <summary>
        /// 触发事件
        /// </summary>
        /// <param name="type"></param>
        /// <param name="data"></param>
        public static void TriggerEvent(EventType type , T data)
        {
            if (eventDic.ContainsKey(type))
            {
                List<Action<T>> list = eventDic[type];
                foreach (var callback in list)
                {
                    callback(data);
                }
            }
        }
    }
    
    public enum EventType
    {
        None = 0,
        Event1 = 1,
        Event2 = 2,
    }
  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    thinkphp使用foreach遍历的方法
    php中foreach中使用&的办法
    thinkphp做搜索功能
    数据库虚拟主机目录的配置文件
    网页响应式设计原理
    数据库常见远程连接问题
  • 原文地址:https://www.cnblogs.com/zjw007/p/6127212.html
Copyright © 2011-2022 走看看