中介者模式:用一个中介者对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
Mediator.h
#ifndef MEDIATOR_H
#define MEDIATOR_H
#include<iostream>
using namespace std;
#include<string>
/**
* 抽象中介类
*/
class Mediator{
public:
// 抽象发送消息方法
virtual void send(string message, int NO) = 0;
};
#endif
Colleague.h
#ifndef COLLEAGUE_H
#define COLLEAGUE_H
#include<iostream>
using namespace std;
#include "Mediator.h"
/**
* 抽象同事类
*/
class Colleague{
protected:
Mediator* mediator;
public:
Colleague(Mediator* med):mediator(med){}
virtual void send(string message) = 0;
virtual void notify(string message) = 0;
virtual int getNO() = 0;
};
#endif
ConcreteMediator.h
#ifndef CONCRETEMEDIATOR_H
#define CONCRETEMEDIATOR_H
#include "Mediator.h"
#include "Colleague.h"
#include<vector>
/**
* 中介具体实现类
*/
class ConcreteMediator : public Mediator{
private:
vector<Colleague*> colls;
public:
void add(Colleague* coll){
colls.push_back(coll);
}
// 中介者根据NO判断,选择接收消息的对象
virtual void send(string message, int NO){
for(Colleague* coll : colls){
if(coll->getNO() == NO){
coll->notify(message);
break;
}
}
}
};
#endif
ConcreteColleague.h
#ifndef CONCRETECOLLEAGUE1_H
#define CONCRETECOLLEAGUE1_H
#include "Colleague.h"
#include "Mediator.h"
/**
* 抽象Colleague的实现类1
*
*/
class ConcreteColleague1 : public Colleague{
private:
int NO;
string message;
public:
ConcreteColleague1(Mediator *med):Colleague(med),NO(1){}
virtual void send(string message){
mediator->send(message, NO);
}
virtual void notify(string message){
cout << message << endl;
}
virtual int getNO(){
return NO;
}
};
/**
* 抽象Colleague的实现类2
*
*/
class ConcreteColleague2 : public Colleague{
private:
int NO;
string message;
public:
ConcreteColleague2(Mediator *med):Colleague(med),NO(2){}
virtual void send(string message){
mediator->send(message, NO);
}
virtual void notify(string message){
cout << message << endl;
}
virtual int getNO(){
return NO;
}
};
#endif
main.cpp
#include "ConcreteMediator.h"
#include "ConcreteColleague.h"
int main(){
ConcreteMediator* mediator = new ConcreteMediator;
Colleague* c1 = new ConcreteColleague1(mediator);
Colleague* c2 = new ConcreteColleague2(mediator);
mediator->add(c1);
mediator->add(c2);
c1->send("干饭");
c2->send("干夜宵");
return 0;
}