#include <iostream>
using namespace std;
class Mediator;
//抽像交互类
class Person{
public:
Person(Mediator * mediator) : m_pMediator(mediator){}
virtual ~Person(){}
virtual void sendMessage(const string & msg) = 0;
virtual void getMessage(const string & msg) = 0;
protected:
Mediator * m_pMediator;
};
//抽像中介者类
class Mediator{
public:
virtual ~Mediator(){}
virtual void setPerson1(Person * person1) = 0;
virtual void setPerson2(Person * person2) = 0;
virtual void send(const string & msg, Person * person) = 0;
};
class Person1 : public Person{
public:
Person1(Mediator * mediator) : Person(mediator){}
void getMessage(const string & msg)override{
cout<<"Person1:"<<msg.data()<<endl;
}
void sendMessage(const string & msg)override{ m_pMediator->send(msg, this); }
};
class Person2 : public Person{
public:
Person2(Mediator * mediator) : Person(mediator){}
void getMessage(const string & msg)override{
cout<<"Person2:"<<msg.data()<<endl;
}
void sendMessage(const string & msg)override{ m_pMediator->send(msg, this); }
};
//具体中介者类
class ConcreteMediator : public Mediator{
public:
virtual void setPerson1(Person * person1)
{
m_person1 = person1;
}
virtual void setPerson2(Person * person2)
{
m_person2 = person2;
}
void send(const string & msg, Person * person){
if(person == m_person1){
m_person2->getMessage(msg);
}else if(person == m_person2){
m_person1->getMessage(msg);
}
}
private:
Person * m_person1;
Person * m_person2;
};
int main()
{
cout << "Hello World!" << endl;
ConcreteMediator * hMediator = new ConcreteMediator;
Person * person1 = new Person1(hMediator);
Person * person2 = new Person2(hMediator);
hMediator->setPerson1(person1);
hMediator->setPerson2(person2);
person1->sendMessage("I am Person1, I send this Message!");
person2->sendMessage("I am Person2, I send this Message!");
delete person1;
person1 = nullptr;
delete person2;
person2 = nullptr;
delete hMediator;
hMediator = nullptr;
return 0;
}