首页 > 编程学习 > 设计模式-消息中心

设计模式-消息中心

发布时间:2022/8/25 17:45:48

单例模板

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

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

Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号