中介模式C++实现

知识的领域是无限的,我们的学习也是无限期的。这篇文章主要讲述中介模式C++实现相关的知识,希望能为你提供帮助。
【中介模式C++实现】中介模式
中介模式是对委托的复杂运用,比如说两个类中,类A中含类B的对象指针作为数据成员,类B中含类A的对象指针作为数据成员。在下面的例子中,中介含有租房者和房东的对象指针,租房者和房东也含有中介的对象指针。完成业务,租房者可以运用其包含的中介对象指针发送给中介包含的房东类的对象的函数成员。房东发送给租房者也一样,具体见代码。

Exe : Mediator.o g++ -o Exe Mediator.o main.o : Mediator.cpp g++ -c -g Mediator.cpp rm : Mediator

#include < iostream> #include < string> using namespace std; //中介模式class Mediator; class Character { public: Mediator* p_Mediator = NULL; virtual void set_Meidator(Mediator* p_Mediator) = 0; virtual void send_msg(string msg) = 0; virtual void get_msg(string msg) = 0; }; class Mediator { public: Character* p_ranter = NULL; Character* p_landlord = NULL; void set_ranter(Character* p_Character); void set_landlord(Character* p_Character); void send_msg(string msg, Character* p_Character); }; void Mediator::set_ranter(Character* p_Character) { this-> p_ranter = p_Character; } void Mediator::set_landlord(Character* p_Character) { this-> p_landlord = p_Character; } void Mediator::send_msg(string msg, Character* p_Character) { if(p_Character == this-> p_ranter) { this-> p_landlord-> get_msg(msg); } else { this-> p_ranter-> get_msg(msg); } }class Renter : public Character { public: void set_Meidator(Mediator* p_Mediator); void send_msg(string msg); void get_msg(string msg); }; void Renter::set_Meidator(Mediator* p_Mediator) { this-> p_Mediator = p_Mediator; } void Renter::send_msg(string msg) { p_Mediator-> send_msg(msg, this); } void Renter::get_msg(string msg) { cout < < "Renter get a msg : " < < msg < < endl; }class Landlord : public Character { public: void set_Meidator(Mediator* p_Mediator); void send_msg(string msg); void get_msg(string msg); }; void Landlord::set_Meidator(Mediator* p_Mediator) { this-> p_Mediator = p_Mediator; } void Landlord::send_msg(string msg) { p_Mediator-> send_msg(msg, this); } void Landlord::get_msg(string msg) { cout < < "Landlord get a msg : " < < msg < < endl; }int main(void) { Renter* p_Renter = new Renter; Landlord* p_Landlord = new Landlord; Mediator* p_Mediator = new Mediator; p_Renter-> set_Meidator(p_Mediator); p_Landlord-> set_Meidator(p_Mediator); p_Mediator-> set_ranter(p_Renter); p_Mediator-> set_landlord(p_Landlord); //renter p_Renter-> send_msg("I am a renter , I want a room with 800RMB/M"); p_Landlord-> send_msg("I am a landlord, I have a room with 800RMB/M"); delete p_Renter; delete p_Landlord; delete p_Mediator; return 0; }


    推荐阅读