又叫最少知识原则

封装一个中间层进行隔离

class AbstractBuilding{
public:
    virtual string getQuality()const = 0;
    virtual void sale() = 0;
};
class BuildingA:public AbstractBuilding{
public:
    BuildingA(){
        m_quality = "高品质";
    }
    string getQuality()const override{
        return m_quality;
    }
    void sale()override{
        cout << "楼盘A:" << m_quality << endl;
    }
private:
    string m_quality;
};
class BuildingB:public AbstractBuilding{
public:
    BuildingB(){
        m_quality = "低品质";
    }
    string getQuality()const override{
        return m_quality;
    }
    void sale()override{
        cout << "楼盘B:" << m_quality << endl;
    }
private:
    string m_quality;
};
// 错误的做法
// 客户端
void test1(){
    string myRequest = "低品质";
    BuildingA* bA = new BuildingA;
    if(bA->getQuality() == myRequest){
        bA->sale();
        delete bA;
    }
    BuildingB* bB = new BuildingB;
    if(bB->getQuality() == myRequest){
        bB->sale();
        delete bB;
    }
}
// 正确做法
// 封装一个中间类
class Mediator{
public:
    Mediator(){
        AbstractBuilding* b = new BuildingA;
        vb.push_back(b);
        b = new BuildingB;
        vb.push_back(b);
    }
    AbstractBuilding* getBuilding(string req){
        for(const auto &b : vb){
            if(b->getQuality() == req){
                return b;
            }
        }
        return NULL;
    }
    ~Mediator(){
        for(auto &b : vb){
            if(b != NULL){
                delete b;
            }
        }
    }
private:
    vector<AbstractBuilding*> vb;
};
// 客户端
void test2(){
    string myRequest = "低品质";
    Mediator m;
    AbstractBuilding* b = m.getBuilding(myRequest);
    if(b != NULL){
        b->sale();
    }
    else{
        cout << "未找到需要的楼盘" << endl;
    }
}
int main()
{
    test2();
    return 0;
}