C++设计模式迪米特法则实例

时间:2021-05-20

迪米特法则(Law of Demeter)又叫作最少知识原则(Least Knowledge Principle 简写LKP),就是说一个对象应当对其他对象有尽可能少的了解,不和陌生人说话。英文简写为: LoD.

类的设计接口尽量封装完善,让外部直接调用

#include<iostream>#include<string>#include<vector>using namespace std; class AbstractBuilding{public: virtual void sale() = 0; virtual string getQuality() = 0; }; class BuildingA :public AbstractBuilding{public: BuildingA() { mQulity = "高品质"; } virtual void sale() { cout << "楼盘A" << mQulity << "被售卖!" << endl; } virtual string getQuality() { return mQulity; } public: string mQulity;}; class BuildingB :public AbstractBuilding{public: BuildingB() { mQulity = "低品质"; } virtual void sale() { cout << "楼盘B" << mQulity << "被售卖!" << endl; } virtual string getQuality() { return mQulity; } public: string mQulity;}; // 中介类class Mediator{public: Mediator() { AbstractBuilding* building = new BuildingA; vBuilding.push_back(building); building = new BuildingB; vBuilding.push_back(building); } // 对外提供接口 AbstractBuilding* findMyBuilding(string quality) { for (vector<AbstractBuilding*>::iterator it = vBuilding.begin(); it != vBuilding.end(); it++) { if ((*it)->getQuality() == quality) { return *it; } } return NULL; } ~Mediator() { for (vector<AbstractBuilding*>::iterator it = vBuilding.begin(); it != vBuilding.end(); it++) { if (*it != NULL) delete *it; } }public: vector<AbstractBuilding*> vBuilding;}; void test01(){ Mediator* mediator = new Mediator; AbstractBuilding* building = mediator->findMyBuilding("低品质"); if (building != NULL) { building->sale(); } else { cout << "没有符号条件的楼盘" << endl; } } int main(){ test01(); system("pause");}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章