单例模板

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("我是员工,我接收到了消息"); });
    }
}

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

原文地址:http://www.cnblogs.com/wuzhongke/p/16901354.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性