中介者模式(Mediator):用一个中介对象来封装一系列的对象交互。中介者使对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
下面是中介者模式的UML图:
下面是C++实现的代码:
/*
* Copyright (c) 2017 initm.com All rights reserved.
* 作者: Stupid
* 描述: 中介者模式
* 完成时间: 2017-12-10 15:15
*/
#include <QCoreApplication>
#include <iostream>
#include <string>
#include <cstdlib>
class Colleague;
class Mediator
{
public:
virtual void Send(const std::string& message, Colleague* colleague) = 0;
};
class Colleague
{
protected:
Mediator* mediator;
public:
Colleague(Mediator* mediator): mediator(mediator){}
};
class ConcreteColleague1: public Colleague
{
public:
ConcreteColleague1(Mediator* mediator): Colleague(mediator){}
void Send(const std::string& message){
mediator->Send(message, this);
}
void Notify(const std::string& message){
std::cout << "同事1收到消息: " << message << std::endl;
}
};
class ConcreteColleague2: public Colleague
{
public:
ConcreteColleague2(Mediator* mediator): Colleague(mediator){}
void Send(const std::string& message){
mediator->Send(message, this);
}
void Notify(const std::string& message){
std::cout << "同事2收到消息: " << message << std::endl;
}
};
class ConcreteMediator: public Mediator
{
private:
ConcreteColleague1* concreteColleague1;
ConcreteColleague2* concreteColleague2;
public:
void SetConcreteColleague1(ConcreteColleague1* concreteColleague1){
this->concreteColleague1 = concreteColleague1;
}
void SetConcreteColleague2(ConcreteColleague2* concreteColleague2){
this->concreteColleague2 = concreteColleague2;
}
void Send(const std::string& message, Colleague* colleague){
if(dynamic_cast<Colleague*>(concreteColleague1) == colleague){
concreteColleague1->Notify(message);
}else if(dynamic_cast<Colleague*>(concreteColleague2) == colleague){
concreteColleague2->Notify(message);
}
}
};
int main(int argc, char *argv[])
{
system("chcp 65001");
QCoreApplication a(argc, argv);
ConcreteMediator* concreteMediator = new ConcreteMediator;
ConcreteColleague1* concreteColleague1 = new ConcreteColleague1(concreteMediator);
ConcreteColleague2* concreteColleague2 = new ConcreteColleague2(concreteMediator);
concreteMediator->SetConcreteColleague1(concreteColleague1);
concreteMediator->SetConcreteColleague2(concreteColleague2);
concreteColleague1->Send("你好,小李");
concreteColleague2->Send("你好,老王");
return a.exec();
}
非常简洁的网站!
支持一个!