概念
中介者模式是一种行为模式, 他的核心思想是通过引入一个中介者对象,将多个对象之间的复杂交互逻辑统一管理。每个对象只需要与中介者通信,而不需要直接与其他对象交互,从而降低系统的耦合度。
适用场景
- 对象之间交互复杂:当对象之间的交互逻辑复杂且难以维护时。
- 减少依赖:当需要减少对象之间的直接依赖时。
- 集中管理交互:当需要集中管理对象之间的交互逻辑时。
创建方式
1、创建一个中介者对象接口,在中介者对象接口中创建一个通知消息函数接口。创建其他的和构件交互的接口也可以。
2、创建同事对象的接口,在此对象中定义一个中介者引用对象。
3、实现具体的中介者对象,在具体的中介者对象中添加一个管理同事对象的数据结构。
1)实现设置函数将同事对象设置给中介者对象(这里可以在构造函数中进行初始化对象设置 ,也可以使用单独的设置函数进行设置)。
2)实现接口中的通知函数,并实现消息的推送。
这里也可以直接在中介者类中创建和销毁组件对象。
4、实现具体的基础构件类,具体的基础构件类中需要实现发送消息通知的函数,并且需要将自己本身添加到中介对象。
5、在客户端创建需要中介者管理的基础构件,在创建一个具体的中介者对象并将需要中介者管理的基础构件以值传递的方式设置到中介者对象中。之后在操作基础构件的时候时候可以通过基础构建中设置的中介者来通知其他的基础构件。
类关系

示例代码
cpp
#include "ZhongJieZheMoShi.h"
int main()
{
std::cout << "欢迎东哥来到设计模式的世界!\n";
IntermediaryBase* intermediary = new ConcretizeIntermediary();
BaseComponent* component1 = new ConcretizeCompent("一:你好,我是第一个好友");
component1->setIntermediary(intermediary);
BaseComponent* component2 = new ConcretizeCompent("二:你好,我是第二个好友");
component2->setIntermediary(intermediary);
BaseComponent* component3 = new ConcretizeCompent("三:你好,我是第三个好友");
component3->setIntermediary(intermediary);
BaseComponent* component4 = new ConcretizeCompent("四:你好,我是第四个好友");
component4->setIntermediary(intermediary);
BaseComponent* component5 = new ConcretizeCompent("五:大家好");
component5->setIntermediary(intermediary);
component5->notify();
}
cpp
#pragma once
#include <vector>
#include <string>
#include <iostream>
using namespace std;
//同事对象
class IntermediaryBase;
class BaseComponent {
public:
BaseComponent() {}
~BaseComponent() {}
virtual void notify() = 0;
virtual void diaplay() = 0;
virtual void setIntermediary(IntermediaryBase* intermediary) = 0;
};
//中介者接口
class IntermediaryBase
{
public:
IntermediaryBase() {}
~IntermediaryBase() {}
virtual void notify() {}
virtual void addComponent(BaseComponent* component) {}
};
//具体中介者
class ConcretizeIntermediary : public IntermediaryBase {
public:
ConcretizeIntermediary() {}
~ConcretizeIntermediary() {}
void notify() {
for (int i = 0; i < m_Component.size(); ++i) {
m_Component[i]->diaplay();
}
}
void addComponent(BaseComponent* component) {
m_Component.push_back(component);
}
vector<BaseComponent*> m_Component;
};
//具体同事对象
class ConcretizeCompent : public BaseComponent {
public:
ConcretizeCompent(string date) { m_date = date; }
~ConcretizeCompent() {}
void notify() {
cout << "五:你好,我是第五个好友" << endl;
m_intermediary->notify();
}
void diaplay() {
cout << m_date << endl;
}
void setIntermediary(IntermediaryBase* intermediary) {
m_intermediary = intermediary;
intermediary->addComponent(this);
}
private:
IntermediaryBase* m_intermediary;
string m_date;
};
csharp
欢迎东哥来到设计模式的世界!
五:你好,我是第五个好友
一:你好,我是第一个好友
二:你好,我是第二个好友
三:你好,我是第三个好友
四:你好,我是第四个好友
五:大家好