1、中介者模式的提出
在软件组件开发过程中,如果存在多个对象,且这些对象之间存在的相互交互的情况不是一一对应的情况,这种功能组件间的对象引用关系比较复杂,耦合度较高。如果有一些新的需求变化,则不易扩展。中介者模式可以解决这种问题。中介者模式使用一个“中介对象”去管理对象间的关联关系,这个中介对象里面定义了对象间的数据统一交互接口,解耦对象间的直接交互依赖,从而提高代码的扩展性。
2、需求描述
有2个线上人员,这两个线上人员可以相互发送和接收对象的消息。设计一个线上人员数据交互的代码,且代码架构便于扩展。
3、中介者模式的代码实现
(1)UML图如下:
(2)代码实现如下:
#include <iostream>
#include <vector>
class Mediator;
class OnlinerPeople
{
protected:
Mediator* mediator;
public:
virtual void sendMsg(std::string msg)=0;
virtual void receiveMsg(std::string msg)=0;
virtual ~OnlinerPeople(){};
};
class Mediator
{
protected:
std::vector<OnlinerPeople*>vecOnlinePeoples;
public:
virtual void sendMessage(std::string msg,OnlinerPeople* pepole)=0;
virtual void addOnliners(OnlinerPeople* people)=0;
virtual ~Mediator(){};
};
class ConcreteMediator:public Mediator
{
public:
void addOnliners(OnlinerPeople* people)override
{
vecOnlinePeoples.emplace_back(people);
};
virtual void sendMessage(std::string msg, OnlinerPeople *pepole) override
{
for(auto it = vecOnlinePeoples.begin();it != vecOnlinePeoples.end(); it++)
{
if( *it != pepole)
{
(*it)->receiveMsg(msg);
}
}
}
};
class OnlinerPeople1:public OnlinerPeople
{
public:
void Init(Mediator* mediator){
this->mediator = mediator;
}
virtual void sendMsg(std::string msg) override
{
std::cout << "OnlinerPeople1 sendMsg: " << std::endl;
mediator->sendMessage(msg,this);
}
virtual void receiveMsg(std::string msg) override
{
std::cout << "OnlinerPeople1 receive msg: " << msg << std::endl;
}
};
class OnlinerPeople2:public OnlinerPeople
{
public:
void Init(Mediator* mediator){
this->mediator = mediator;
}
virtual void sendMsg(std::string msg) override
{
std::cout << "OnlinerPeople2 sendMsg: " << std::endl;
mediator->sendMessage(msg,this);
}
virtual void receiveMsg(std::string msg) override
{
std::cout << "OnlinerPeople2 receive msg: " << msg << std::endl;
}
};
class Client
{
private:
Mediator* mediator{nullptr};
OnlinerPeople1 people1;
OnlinerPeople2 people2;
public:
Client(Mediator* p){
mediator = p;
people1.Init(mediator);
people2.Init(mediator);
};
void DoWork()
{
mediator->addOnliners(&people1);
mediator->addOnliners(&people2);
people1.sendMsg("hello people2");
people2.sendMsg("hello people1");
};
};
int main()
{
Mediator* mediator = new ConcreteMediator();
Client obj(mediator);
obj.DoWork();
delete mediator;
mediator = nullptr;
return 0;
}
程序运行结果如下: