设计模式之中介者模式

设计模式之中介者模式,第1张

设计模式之中介者模式(Mediator)

中间者模者模式原理:中介者维持所有要交互对象指针或者对象,所有对象维持一个中介者的指针或者对象。


#include <iostream>
#include <string> using namespace std; class Mediator;
class Person
{
public:
virtual GetMessage(string message)
{ }
virtual void SendMessage(string message)
{ }
virtual void SetMediator(Mediator *pmdiator)
{ }
protected:
Mediator *m_pmediator;
}; class Mediator
{
public:
void Send(string message,Person *person)
{
if (person == m_renter)
{
m_landlord->GetMessage(message);
}
else
{
m_renter->GetMessage(message);
}
}
void SetRenter(Person *prenter)
{
m_renter = prenter;
}
void SetLandlord(Person *plandlord)
{
m_landlord = plandlord;
}
private:
Person *m_renter;
Person *m_landlord;
}; class Renter:public Person
{
public:
virtual GetMessage(string message)
{
cout << "租客收到租房信息:"<<message<<endl;
}
virtual void SendMessage(string message)
{
m_pmediator->Send(message,this);
}
virtual void SetMediator(Mediator *pmediator)
{
m_pmediator = pmediator;
}
};
class Landlord:public Person
{
public:
virtual GetMessage(string message)
{
cout << "房东收到租房信息:"<<message<<endl;
}
virtual void SendMessage(string message)
{
m_pmediator->Send(message,this);
}
virtual void SetMediator(Mediator *pmediator)
{
m_pmediator = pmediator;
}
}; int main()
{
Mediator *pmediator = new Mediator();
Person *prenter = new Renter();
Person *plandlord = new Landlord(); pmediator->SetLandlord(plandlord);
pmediator->SetRenter(prenter);
prenter->SetMediator(pmediator);
plandlord->SetMediator(pmediator); prenter->SendMessage("我要租一个有网的房子");
plandlord->SendMessage("我现在有一个两室一厅的房子要出租");
return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/588636.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存