C++演示中介模式
避免两个模块之间的耦合,使用中介模式解决。下面是C++代码
#include <iostream>
#include <vector>
using namespace std;
class client;
//中介
class mediator {
public:
void addclient(client* client) {
clientVec.push_back(client);
}
void send(const std::string &str,client* cli);
private:
std::vector<client*> clientVec;
};
//客户端
class client {
public:
client(mediator* ator,const std::string& name) :mediator(ator),name(name) {
};
void sendmsg(const std::string& str){
mediator->send(str,this);
}
void getMsg(const std::string& str) {
std::cout << name << "接收到的消息是:" << str << std::endl;
}
private:
mediator *mediator = nullptr;
std::string name;
};
int main() {
mediator media;
client clientA(&media,"甲");
client clientB(&media, "乙");
client clientC(&media, "丙");
media.addclient(&clientA);
media.addclient(&clientB);
media.addclient(&clientC);
clientA.sendmsg("你好");
clientB.sendmsg("你们好啊");
return 0;
}
void mediator::send(const std::string &str,client* cli)
{
for (auto &client : clientVec) {
if (client != cli) {
client->getMsg(str);
}
}
}
上面这段程序中,mediator中的send采取了遍历添加进来的客户端数组,然后判断是不是发送消息的自身,如果不是,就调用其getMsg函数。程序输出如下
上面这段程序可以根据具体业务的不同,在send函数中实现不同的逻辑,或者是别的什么功能。主要是为了放置client对自身的相互引用,然后提供一个类似于工作台的一块空间。