初学者,自用笔记

观察者模式-简单unity事件中心(基于UnityAction)

用例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public interface IEventInfo
{ };

public class EventInfo<T> : IEventInfo
{
    public UnityAction<T> actions;
    public EventInfo(UnityAction<T> action)
    {
        this.actions = action;
    }
}

public class EventInfo : IEventInfo
{
    public UnityAction actions;
    public EventInfo(UnityAction action)
    {
        this.actions = action;
    }
}

// 被观察者接口:定义被观察者必须实现的行为
public interface IObserver
{
    string EventName { get; } // 订阅的事件名称
    void Subscribe(); // 订阅事件
    void Unsubscribe(); // 取消订阅
    void OnEventTrigger(); // 无参事件响应
    void OnEventTrigger<T>(T param); // 带参事件响应
}

public class EventCenter : TheManager<EventCenter> 
{
    //存储所有事件
    private Dictionary<string,IEventInfo> allEvent = new Dictionary<string, IEventInfo>();

    //添加无参事件
    public void AddEventList(string _name,UnityAction _action)
    {
        if(allEvent.ContainsKey(_name))
        {
            //将新方法添加到已有事件的委托链中
            (allEvent[_name] as EventInfo).actions += _action;
        }
        else
        {
            // 不存在则创建新的事件信息对象并添加到字典
            allEvent.Add(_name, new EventInfo(_action));
        }

    }

    // 添加带参数的泛型事件
    public void AddEventList<T>(string _name, UnityAction<T> _action)
    {
        if (allEvent.ContainsKey(_name))
        {
            // 将新方法添加到已有泛型事件的委托链中
            (allEvent[_name] as EventInfo<T>).actions += _action;
        }
        else
        {
            // 不存在则创建新的泛型事件信息对象并添加到字典
            allEvent.Add(_name, new EventInfo<T>(_action));
        }
    }

    // 触发无参事件
    public void TriggerEvent(string _name)
    {
        // 检查事件是否存在
        if (allEvent.TryGetValue(_name, out IEventInfo eventInfo))
        {
            // 转换为无参事件类型并调用
            EventInfo info = eventInfo as EventInfo;
            if (info != null && info.actions != null)
            {
                info.actions.Invoke();
            }
        }
    }

    // 触发带参数的泛型事件
    public void TriggerEvent<T>(string _name, T _param)
    {
        // 检查事件是否存在
        if (allEvent.TryGetValue(_name, out IEventInfo eventInfo))
        {
            // 转换为对应泛型事件类型并调用
            EventInfo<T> info = eventInfo as EventInfo<T>;
            if (info != null && info.actions != null)
            {
                info.actions.Invoke(_param);
            }
        }
    }

    // 移除无参事件
    public void RemoveEvent(string _name, UnityAction _action)
    {
        if (allEvent.TryGetValue(_name, out IEventInfo eventInfo))
        {
            EventInfo info = eventInfo as EventInfo;
            if (info != null)
            {
                // 从委托链中移除指定方法
                info.actions -= _action;
            }
        }
    }

    // 移除带参数的泛型事件
    public void RemoveEvent<T>(string _name, UnityAction<T> _action)
    {
        if (allEvent.TryGetValue(_name, out IEventInfo eventInfo))
        {
            EventInfo<T> info = eventInfo as EventInfo<T>;
            if (info != null)
            {
                // 从委托链中移除指定方法
                info.actions -= _action;
            }
        }
    }

    // 清空所有事件
    public void ClearAllEvents()
    {
        allEvent.Clear();
        // 可选:重置单例(根据需求决定是否需要)
        // instance = null;
    }

    // 移除指定名称的事件
    public void RemoveEventByName(string _name)
    {
        if (allEvent.ContainsKey(_name))
        {
            allEvent.Remove(_name);
        }
    }

}

接口化组件观察者

public abstract class ObserverComponent : MonoBehaviour, IObserver
{
    // 子类指定事件名称
    public string EventName { get; }

    // 订阅事件(子类重写实现具体订阅逻辑)
    public virtual void Subscribe()
    {
        if (string.IsNullOrEmpty(EventName))
        {
            Debug.LogError($"{gameObject.name}:事件名为空,订阅失败!");
            return;
        }
    }

    // 取消订阅(子类重写实现具体取消逻辑)
    public virtual void Unsubscribe()
    {
        if (string.IsNullOrEmpty(EventName)) return;
    }

    // 无参事件响应逻辑(子类实现)
    public virtual void OnEventTrigger();

    // 带参事件响应逻辑(子类实现)
    public virtual void OnEventTrigger<T>(T param);

    // 组件激活时订阅
    protected virtual void OnEnable()
    {
        Subscribe();
    }

    // 组件禁用时取消订阅
    protected virtual void OnDisable()
    {
        Unsubscribe();
    }

    // 组件销毁时再次取消订阅
    protected virtual void OnDestroy()
    {
        Unsubscribe();
    }
}

观察者模式-简单unity事件中心(基于C#原生Action)

public interface IEventInfo { }

public class EventInfo<T> : IEventInfo
{
    public Action<T> actions;
    public EventInfo(Action<T> action)
    {
        this.actions = action;
    }
}

public class EventInfo : IEventInfo
{
    public Action actions;
    public EventInfo(Action action)
    {
        this.actions = action;
    }
}

public interface IObserver
{
    string EventName { get; } // 订阅的事件名称
    void Subscribe(); // 订阅事件
    void Unsubscribe(); // 取消订阅
    void OnEventTrigger(); // 无参事件响应
    void OnEventTrigger<T>(T param); // 带参事件响应
}

// 单例事件中心
public class EventCenter : TheManager<EventCenter>
{
    private Dictionary<string, IEventInfo> allEvent = new Dictionary<string, IEventInfo>();

    #region 无参事件操作
    // 添加无参事件订阅
    public void AddEventList(string eventName, Action action)
    {
        if (allEvent.ContainsKey(eventName))
        {
            (allEvent[eventName] as EventInfo).actions += action;
        }
        else
        {
            allEvent.Add(eventName, new EventInfo(action));
        }
    }

    // 触发无参事件
    public void TriggerEvent(string eventName)
    {
        if (allEvent.TryGetValue(eventName, out IEventInfo eventInfo))
        {
            EventInfo info = eventInfo as EventInfo;
            info?.actions?.Invoke();
        }
    }

    // 移除无参事件订阅
    public void RemoveEventList(string eventName, Action action)
    {
        if (allEvent.TryGetValue(eventName, out IEventInfo eventInfo))
        {
            EventInfo info = eventInfo as EventInfo;
            info?.actions -= action;
        }
    }
    #endregion

    #region 带参泛型事件操作
    // 添加带参事件订阅
    public void AddEventList<T>(string eventName, Action<T> action)
    {
        if (allEvent.ContainsKey(eventName))
        {
            (allEvent[eventName] as EventInfo<T>).actions += action;
        }
        else
        {
            allEvent.Add(eventName, new EventInfo<T>(action));
        }
    }

    // 触发带参事件
    public void TriggerEvent<T>(string eventName, T param)
    {
        if (allEvent.TryGetValue(eventName, out IEventInfo eventInfo))
        {
            EventInfo<T> info = eventInfo as EventInfo<T>;
            info?.actions?.Invoke(param);
        }
    }

    // 移除带参事件订阅
    public void RemoveEventList<T>(string eventName, Action<T> action)
    {
        if (allEvent.TryGetValue(eventName, out IEventInfo eventInfo))
        {
            EventInfo<T> info = eventInfo as EventInfo<T>;
            info?.actions -= action;
        }
    }
    #endregion

    // 清空所有事件
    public void ClearAllEvents() => allEvent.Clear();

    // 根据名称移除事件
    public void RemoveEventByName(string eventName)
    {
        if (allEvent.ContainsKey(eventName))
            allEvent.Remove(eventName);
    }
}