目的:解决多组件之间的通信问题,使得组件之间的通信变得简单
核心:提供一个管理类,用来处理组件之间的通信,所有的组件只和管理类通信,组件彼此之间不在单独通信
例子:
class Mediator
{
public:
virtual void Send(string &message, Person *person) = 0;
virtual void SetRenter(Person *renter) = 0;
virtual void SetLandlord(Person *landlord) = 0;
};
class Person
{
public:
virtual void SetMediator(Mediator *mediator) = 0;
virtual void SendMessage(string message) = 0;
virtual void GetMessage(string message) = 0;
protected:
Mediator *p_mediator;
};
class Renter: public Person
{
public:
void SetMediator(Mediator *mediator)
{
p_mediator = mediator;
}
void SendMessage(string message)
{
p_mediator->Send(message, this);
}
void GetMessage(string message)
{
cout << "租房者收到房东发来的消息:"<< message << endl;
}
};
class Landlord: public Person
{
public:
void SetMediator(Mediator *mediator)
{
p_mediator = mediator;
}
void SendMessage(string message)
{
p_mediator->Send(message,this);
}
void GetMessage(string message)
{
cout << "房东收到租客发来的消息:" << message << endl;
}
};
class HouseMediator: public Mediator
{
private:
Person *p_renter;
Person *p_landlord;
public:
HouseMediator(): p_renter(NULL), p_landlord(NULL)
{
}
void SetRenter(Person *renter)
{
p_renter = renter;
}
void SetLandlord(Person *landlord)
{
p_landlord = landlord;
}
void Send(string &message, Person *person) //消息的处理函数
{
if(person == p_renter)
p_landlord->GetMessage(message);
else
p_renter->GetMessage(message);
}
};
int main()
{
Renter* r = new Renter();
Landlord* l = new Landlord();
HouseMediator* hm = new HouseMediator();
r->SetMediator(hm);
l->SetMediator(hm);
hm->SetRenter(r);
hm->SetLandlord(l);
r->SendMessage(string("东西坏了,房东快来修理!"));
l->SendMessage(string("到时间了,该叫房租了!"));
return 0;
}