迪米特法则
又叫最少知识原则 封装一个中间层进行隔离 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....