中介者模式是用一个中介类来封装一系列的对象交互,对象间无需相互引用,降低了耦合性。中介类可以根据需要改变他们之间的交互。
中介者模式可以使用租房案例来描述,房东不需要单独找房客,房客也不需要单独找房东,房产中介将房东和租客信息整合到一起
class iagency {
public:
virtual void sendmsg(const std::string& msg, const std::string& id) = 0;
};
class icustom {
public:
virtual void sendmsg(const std::string& msg) = 0;
virtual void getmsg(const std::string& msg) = 0;
};
class landlord : public icustom {
public:
landlord(const std::shared_ptr<iagency>& sp) : sp_iagency_(sp) {
id_ = "12121212121";
}
void sendmsg(const std::string& msg) {
if (sp_iagency_) {
sp_iagency_->sendmsg(msg, id_);
}
}
void getmsg(const std::string& msg) {
std::cout << msg << std::endl;
}
std::string getid() {
return id_;
}
private:
std::string id_;
std::shared_ptr<iagency> sp_iagency_;
};
class renter : public icustom {
public:
renter(const std::shared_ptr<iagency>& sp) : sp_iagency_(sp) {
id_ = "2342342342342342";
}
void sendmsg(const std::string& msg) {
if (sp_iagency_) {
sp_iagency_->sendmsg(msg, id_);
}
}
void getmsg(const std::string& msg) {
std::cout << msg << std::endl;
}
std::string getid() {
return id_;
}
private:
std::string id_;
std::shared_ptr<iagency> sp_iagency_;
};
class houseagency : public iagency {
public:
void setlandlord(const std::string& id, const std::shared_ptr<landlord>& sp) { map_landlords_[id] = sp; }
void setrenter(const std::string& id, const std::shared_ptr<renter>& sp) { map_renters_[id] = sp; }
void sendmsg(const std::string& msg, const std::string& id) {
auto it = map_landlords_.find(id);
if (it != map_landlords_.end()) {
for (auto itor = map_renters_.begin(); itor != map_renters_.end(); itor++) {
if (itor->second) {
itor->second->getmsg(msg);
}
}
}
}
private:
std::map<std::string, std::shared_ptr<landlord>> map_landlords_;
std::map<std::string, std::shared_ptr<renter>> map_renters_;
};
int main() {
{
std::shared_ptr<houseagency> sp_houseagency = std::make_shared<houseagency>();
std::shared_ptr<landlord> sp_landlord = std::make_shared<landlord>(sp_houseagency);
std::shared_ptr<renter> sp_renter = std::make_shared<renter>(sp_houseagency);
sp_houseagency->setlandlord(sp_landlord->getid(), sp_landlord);
sp_houseagency->setrenter(sp_renter->getid(), sp_renter);
sp_landlord->sendmsg("i have a house to rent");
}
}