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对自身的相互引用,然后提供一个类似于工作台的一块空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值