设计模式_中介者模式

中介者模式

介绍

|------|------------------------------------------------------------|---------|---------------------|-----------------|
| 设计模式 | 定义 | 案例 | 问题堆积在哪里 | 解决办法 |
| 中介者 | 代替了多个对象之间的互动 使对象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点吃饭!");
    }
}

结果

总结

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

相关推荐
Geoking.1 小时前
【UML】面向对象中类与类之间的关系详解
设计模式·uml
希望_睿智7 小时前
实战设计模式之中介者模式
c++·设计模式·架构
有一个好名字12 小时前
设计模式-观察者模式
观察者模式·设计模式
青柠代码录14 小时前
【设计模式】A1-单例模式
单例模式·设计模式
阿闽ooo1 天前
深入浅出适配器模式:从跨国插头适配看接口兼容的艺术
c++·设计模式·适配器模式
Kiyra1 天前
WebSocket vs HTTP:为什么 IM 系统选择长连接?
分布式·websocket·网络协议·http·设计模式·系统架构·wpf
山沐与山1 天前
【设计模式】Python责任链模式:从入门到实战
python·设计模式·责任链模式
繁星星繁1 天前
【项目】基于SDK实现的智能聊天助手(使用api接入deepseek)------(二)
c++·设计模式·学习方法
职业码农NO.11 天前
系统架构设计中的 15 个关键取舍
设计模式·架构·系统架构·ddd·架构师·设计规范·领域驱动