设计模式_中介者模式

中介者模式

介绍

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

结果

总结

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

相关推荐
静水流深_沧海一粟6 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder6 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室14 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦1 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式
电子科技圈5 天前
XMOS推动智能音频等媒体处理技术从嵌入式系统转向全新边缘计算
人工智能·mcu·物联网·设计模式·音视频·边缘计算·iot
徐先生 @_@|||5 天前
安装依赖三方exe/msi的软件设计模式
设计模式