04.事件中心模块
一、事件中心模块的作用:
降低程序耦合性,减小程序复杂度。
二、什么是观察者设计模式
观察者设计模式(Observer Design Pattern)是一种行为型设计模式,它定义了对象之间的一对多依赖关系:当一个对象(被观察者)的状态发生变化时,所有依赖它的对象(观察者)会自动收到通知并更新。
这种模式的核心思想是解耦被观察者和观察者,让它们可以独立变化,同时保持联动。
三、简单的事件中心模块代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/// <summary>
/// 事件中心 单例模式对象
/// </summary>
public class EventCenter : BaseManager<EventCenter>
{private Dictionary<string, UnityAction<object>> eventDic = new Dictionary<string, UnityAction<object>>();//key :事件的名字//value: 监听这个事件的对应的委托函数们/// <summary>/// 添加事件监听/// </summary>/// <param name="name">事件的名字</param>/// <param name="action">准备用来处理事件的委托函数</param>public void AddEventLisner(string name,UnityAction<object> action){if(eventDic.ContainsKey (name)){eventDic[name] += action;//委托的基本用法}else{eventDic.Add(name, action);}}/// <summary>/// 移除对应的事件监听,若监听事件的对象被销毁而没有移除事件监听/// 会导致内存泄露(无法触发垃圾回收)/// </summary>/// <param name="name">事件的名字</param>/// <param name="action">对应之前添加的委托函数</param>public void RemovaEventLisner(string name,UnityAction<object> action)//在 OnDestroy()生命周期函数中调用{if(eventDic.ContainsKey (name)){eventDic[name] -= action;}}/// <summary>/// 事件触发/// </summary>/// <param name="name">哪个事件触发了(名字)</param>public void EventTrigger(string name,object info){if(eventDic.ContainsKey (name)){//eventDic[name]();//另一种写法eventDic[name].Invoke(info);//执行这个委托监听的所有委托函数}}/// <summary>/// 清空事件中心,主要用在场景切换时/// 防止有监听函数没有被移除/// </summary>public void Clear(){eventDic.Clear();}
}