订阅发布者模式-消息中心

单例模板

public abstract class Singleton<T> where T : new() {
    private static T instance;
    public static T Instance {
        get {
            if (instance == null)
                instance = new T();
            return instance;
        }
        set => instance = value;
    }
}

消息中心

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

// 消息中心
public class MessageCenter : Singleton<MessageCenter> {
    // 存储消息
    private Dictionary<string, Dictionary<GameObject, Action>> messages = new Dictionary<string, Dictionary<GameObject, Action>>();

    // 订阅消息
    public void Ding_Yue_Xiao_Xi(string ding_yue_de_xiao_xi, GameObject shei, Action zuo_de_shi) {
        if (!messages.ContainsKey(ding_yue_de_xiao_xi)) {
            messages.Add(ding_yue_de_xiao_xi, new Dictionary<GameObject, Action>());
        }

        Dictionary<GameObject, Action> tempDic = messages[ding_yue_de_xiao_xi];

        if (!tempDic.ContainsKey(shei))
            tempDic.Add(shei, zuo_de_shi);
        else
            tempDic[shei] = zuo_de_shi;
    }

    public void Fa_Bu_Xiao_Xi(string zhi_ding_xiao_xi) {
        if (messages.ContainsKey(zhi_ding_xiao_xi)) {
            foreach (var item in messages[zhi_ding_xiao_xi]) {
                item.Value();
            }
        }
    }
}

老板

using UnityEngine;

// 老板
public class Boss : MonoBehaviour {

    void Start() {
        MessageCenter.Instance.Ding_Yue_Xiao_Xi("发布任务", gameObject, () => { Debug.Log("我是老板,我要发布任务"); });
    }

    [ContextMenu("测试执行")]
    public void Test() {
        MessageCenter.Instance.Fa_Bu_Xiao_Xi("发布任务");
    }
}

员工大鸟

using UnityEngine;

// 员工大鸟
public class BigBird : MonoBehaviour {
    void Start() {
        MessageCenter.Instance.Ding_Yue_Xiao_Xi("发布任务", gameObject, () => { Debug.Log("我是员工,我接收到了消息"); });
    }
}

消息中心是在观察者模式下进一步的细化,将彼此之间的代码彻底的拆分
通过中间的消息中心使得订阅者和发布者之间没有一定的联系。

posted @   坞中客  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示