[C++] 纯文本查看 复制代码 #include <iostream>
using namespace std;
namespace mediator_pattern {
class abstract_person;
// 抽象中介
class abstract_mediator {
public:
virtual void set_obj1(abstract_person *person) = 0;
virtual void set_obj2(abstract_person *person) = 0;
virtual void send_msg(abstract_person *person, string msg) = 0;
virtual ~abstract_mediator() {}
};
// 抽象人
class abstract_person {
public:
virtual void set_mediator(abstract_mediator *mediator) = 0;
virtual void send(string msg) = 0;
virtual void get(string msg) = 0;
virtual ~abstract_person() {}
protected:
abstract_mediator *m_mediator;
};
// 男人
class man : public abstract_person {
public:
virtual void set_mediator(abstract_mediator *mediator) override {
this->m_mediator = mediator;
}
virtual void send(string msg) override {
this->m_mediator->send_msg(this, msg);
}
virtual void get(string msg) override {
printf("收到信息:%s\n", msg.c_str());
}
};
// 女人
class woman : public abstract_person {
public:
virtual void set_mediator(abstract_mediator *mediator) override {
this->m_mediator = mediator;
}
virtual void send(string msg) override {
this->m_mediator->send_msg(this, msg);
}
virtual void get(string msg) override {
printf("收到信息:%s\n", msg.c_str());
}
};
// qq 辅助类
class qq : public abstract_mediator {
public:
qq() : m_one{}, m_two{} {}
virtual void set_obj1(abstract_person *person) override {
this->m_one = person;
}
virtual void set_obj2(abstract_person *person) override {
this->m_two = person;
}
void send_msg(abstract_person *person, string msg) override {
if (person == this->m_one)
this->m_one->get(msg);
else if (person == this->m_two)
this->m_two->get(msg);
else
return;
}
abstract_person *m_one;
abstract_person *m_two;
};
}
// 可以看出通过中介者模式 可以有效的解耦类与类之间的相互引用
int main(void)
{
using namespace mediator_pattern;
abstract_person *m = new man;
abstract_person *wm = new woman;
abstract_mediator *q = new qq;
q->set_obj1(m);
q->set_obj2(wm);
m->set_mediator(q);
wm->set_mediator(q);
m->send("爱你,宝贝");
wm->send("我也爱你宝贝");
delete q;
delete wm;
delete m;
return 0;
} |