中介者模式
调停者模式包装了一系列对象相互作用的方式,使得这些对象不必相互明显作用。从而使他们可以松散偶合。当某些 对象之间的作用发生改变时,不会立即影响其他的一些对象之间的作用。保证这些作用可以彼此独立的变化。调停者模式将多对多的相互作用 转化为一对多的相互作用。调停者模式将对象的行为和协作抽象化,把对象在小尺度的行为上与其他对象的相互作用分开处理。
假设现在科技发达之后,家里所有设备都是智能化的,而小明在家洗澡的时候有个习惯就是喜欢听歌,而且洗澡时候还要把窗帘拉上。因此就有这种情形,小明要拉窗帘可能就是要洗澡,当然也要听歌,因此我们希望小明家的洗浴设备,音响设备和窗帘设备都能协同合作,不管操作哪种设备,其他两种设备都有一定响应。
#include <iostream>
using namespace std;
class Mediator;
class Person{
public:
Person(string name, int sex, int condition, Mediator* mediator) {
this->name=name;
this->sex=sex;
this->condition=condition;
this->mediator=mediator;
}
virtual ~Person(){}
int getCondition() {
return condition;
}
int getSex() {
return sex;
}
string getName() {
return name;
}
virtual void getParter(Person* p) = 0;
protected:
string name;
int sex;
int condition;
Mediator* mediator;
};
class Mediator{
public:
void getParter(){
if(man->getSex() == woman->getSex()){
cout << "I am not gay" << endl;
return;
}
if (man->getCondition() == woman->getCondition()) {
cout << man->getName() << "==" << woman->getName() << endl;
} else {
cout << man->getName() << "!=" << woman->getName() << endl;
}
}
void setMan(Person* man) {
this->man = man;
}
void setWoman(Person* woman) {
this->woman = woman;
}
private:
Person* man;
Person* woman;
};
class Woman : public Person{
public:
Woman(string name, int sex, int condition, Mediator* mediator): Person(name, sex, condition, mediator) {
}
int getCondition() {
return condition;
}
virtual void getParter(Person* p) {
mediator->setWoman(this);
mediator->setMan(p);
mediator->getParter();
}
};
class Man: public Person {
public:
Man(string name, int sex, int condition, Mediator* mediator): Person(name, sex, condition, mediator) {
}
int getCondition() {
return condition;
}
virtual void getParter(Person* p) {
mediator->setMan(this);
mediator->setWoman(p);
mediator->getParter();
}
};
int main()
{
Mediator* mediator = new Mediator;
Person* woman1 = new Woman("woman1", 0, 5, mediator);
Person* woman2 = new Woman("woman2", 0, 5, mediator);
Person* man1 = new Man("man1", 1, 6, mediator);
Person* man2 = new Man("man2", 1, 5, mediator);
woman1->getParter(woman2);
woman2->getParter(man1);
woman2->getParter(man2);
delete woman1;
delete woman2;
delete man1;
delete man2;
delete mediator;
return 0;
}