行为型模型 中介者模式
Mediator抽象中介者
中介者类的抽象父类。
concreteMediator
具体的中介者类。
Colleague
关联类的抽象父类。
concreteColleague
具体的关联类。
适用于:
用一个中介对象,封装一些列对象(同事)的交换,中介者是各个对象不需要显示的相互作用,从而实现了耦合松散,而且可以独立的改变他们之间的交换。
/** * 行为型模型 中介者模式 * Mediator模式也叫中介者模式,是由GoF提出的23种软件设计模式的一种。 * Mediator模式是行为模式之一,在Mediator模式中,类之间的交互行为被统一放在Mediator的对象中,对象通过Mediator对象同其他对象交互,Mediator对象起着控制器的作用。 * */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <list> // 前置声明 class Mediator; class Person { public: Person(std::string name, int sex, int condit, Mediator * mediator) { m_name = name; m_sex = sex; m_condit = condit; m_mediator = mediator; } std::string getName() { return m_name; } int getSex() { return m_sex; } int getCondit() { return m_condit; } Mediator * getMediator() { return m_mediator; } virtual void getParter(Person *p) = 0; virtual ~Person() {}; private: std::string m_name; int m_sex; int m_condit; Mediator * m_mediator; }; class Mediator { public: Mediator() { pMan = nullptr; pWoman = nullptr; } void setWoman(Person *p) { pWoman = p; } void setMan(Person *p) { pMan = p; } void getParter() { if (pMan->getSex() == pWoman->getSex() ) { std::cout << "No No No 我不是同性恋" << std::endl; } if (pMan->getCondit() == pWoman->getCondit()) { std::cout << pMan->getName() << " 和 " << pWoman->getName() << " 绝配" << std::endl; } else { std::cout << pMan->getName() << " 和 " << pWoman->getName() << " 不配" << std::endl; } } private: Person * pMan; Person * pWoman; }; class Man: public Person { public: Man(std::string name, int sex, int contid, Mediator * mediator): Person(name, sex, contid, mediator) { } virtual void getParter(Person *p) { this->getMediator()->setMan(this); this->getMediator()->setWoman(p); this->getMediator()->getParter(); } }; class Woman: public Person { public: Woman(std::string name, int sex, int contid, Mediator * mediator): Person(name, sex, contid, mediator) { } virtual void getParter(Person *p) { this->getMediator()->setMan(p); this->getMediator()->setWoman(this); this->getMediator()->getParter(); } }; void mytest() { Mediator * mediator = new Mediator(); Woman * w1 = new Woman("小芳", 2, 4, mediator); Man * m1 = new Man("张三", 1, 3, mediator); Man * m2 = new Man("李四", 1, 4, mediator); w1->getParter(m1); w1->getParter(m2); delete m1; m1 = nullptr; delete m2; m2 = nullptr; delete w1; w1 = nullptr; delete mediator; mediator = nullptr; return; } int main() { mytest(); system("pause"); return 0; }