中介者模式

中介者模式是用一个中介类来封装一系列的对象交互,对象间无需相互引用,降低了耦合性。中介类可以根据需要改变他们之间的交互。
中介者模式可以使用租房案例来描述,房东不需要单独找房客,房客也不需要单独找房东,房产中介将房东和租客信息整合到一起

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");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容