设计模式_中介者模式

中介者模式

介绍

|------|------------------------------------------------------------|---------|---------------------|-----------------|
| 设计模式 | 定义 | 案例 | 问题堆积在哪里 | 解决办法 |
| 中介者 | 代替了多个对象之间的互动 使对象1 2 3 之间的互动 变为: 对象1->中介 对象2->中介 对象3->中介 | 好友之间 约饭 | 好友1 通知 好友2 -3 -4 等等 | 加一个群 谁想吃饭就 通知一下 |

类图

代码

角色

BasePeople // 基类

FriendA

FriendB

FriendC

FriendGroup // 群

BasePeople

cs 复制代码
public abstract class BasePeople
{
    public string name;

    public abstract void ReceiverMsg(string msg);

    public abstract void Send(string msg);
}

FriendA

cs 复制代码
using UnityEngine;

public class FriendA : BasePeople
{
    FriendA() { }
    public FriendA(string name)
    {
        this.name = name;
    }

    public override void ReceiverMsg(string msg)
    {
        Debug.Log(name + "接收:" + msg);
    }

    public override void Send(string msg)
    {
        Debug.Log(name + "发送:" + msg);
        FriendGroup.GetIns().SendAllPeopleMsg(name, msg);
    }
}

FriendB 类似A

FriendC类似A

FriendGroup

cs 复制代码
using System.Collections.Generic;

public class FriendGroup 
{
   //---------------------------------------------
    static FriendGroup self = null;
    private FriendGroup() { }
    public static  FriendGroup GetIns()
    {
        if (null == self)
        {
            self = new FriendGroup();
        }

        return self;
    }

    //--------------------------------------------

    List<BasePeople> gruop = new List<BasePeople>();

    // 添加
    public void AddPeople(BasePeople friend)
    {
        if (null == friend)
            return;

        gruop.Add(friend);
    }

    // 发送
    public void SendAllPeopleMsg(string senderName, string msg)
    {
        foreach (var item in gruop)
        {
            if (senderName != item.name)
            {
                item.ReceiverMsg(msg);
            }
        }
    }

}

测试代码

cs 复制代码
using UnityEngine;

public class TestZJZ : MonoBehaviour
{
    void Start()
    {
        // 创建people
        BasePeople p1 = new FriendA("P1");
        BasePeople p2 = new FriendA("P2");
        BasePeople p3 = new FriendA("P3");

        // 创建群
        FriendGroup group = FriendGroup.GetIns();
        group.AddPeople(p1);
        group.AddPeople(p2);
        group.AddPeople(p3);

        p3.Send("晚上8点吃饭!");
    }
}

结果

总结

在 多对象之间互相通信 提炼出一个中介者 ,会让类图变得简单漂亮

相关推荐
kisshyshy1 小时前
从无崖子到OpenAI:大模型间的“传功”,动了谁的奶酪?
人工智能·深度学习·设计模式
咖啡八杯6 小时前
GoF设计模式——责任链模式
设计模式·面试·架构
大辉狼_音频架构1 天前
Vol.01 高频设计模式
设计模式
我登哥MVP1 天前
走进 Gang of Four 设计模式:代理模式
设计模式·代理模式
我登哥MVP1 天前
走进 Gang of Four 设计模式:外观模式
java·设计模式·外观模式
ttod_qzstudio2 天前
【软考设计模式】备忘录模式:对象状态的捕获与无损恢复精讲
设计模式·备忘录模式
ttod_qzstudio2 天前
【软考设计模式】责任链模式:请求传递的多级处理与发送接收解耦精讲
设计模式·责任链模式
2501_914245932 天前
C语言设计模式详解:从理论到实践的完整指南
c语言·开发语言·设计模式
CaffeinePro2 天前
四⼤极简架构原则KISS/DRY/YAGNI/LOD
设计模式·架构
霸道流氓气质2 天前
SpringBoot中设计模式组合使用示例-策略、模板、观察者、门面、工厂、单例。
spring boot·后端·设计模式