订阅发布者模式-消息中心
单例模板
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("我是员工,我接收到了消息"); });
}
}
消息中心是在观察者模式下进一步的细化,将彼此之间的代码彻底的拆分
通过中间的消息中心使得订阅者和发布者之间没有一定的联系。
本文来自博客园,作者:坞中客,转载请注明原文链接:https://www.cnblogs.com/wuzhongke/p/16901354.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?