這篇文章將為大家詳細(xì)講解有關(guān)C++設(shè)計(jì)模式迪米特法則的示例分析,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
定制網(wǎng)站建設(shè)可以根據(jù)自己的需求進(jìn)行定制,網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)構(gòu)思過(guò)程中功能建設(shè)理應(yīng)排到主要部位公司網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)的運(yùn)用實(shí)際效果公司網(wǎng)站制作網(wǎng)站建立與制做的實(shí)際意義
迪米特法則(Law of Demeter)又叫作最少知識(shí)原則(Least Knowledge Principle 簡(jiǎn)寫(xiě)LKP),就是說(shuō)一個(gè)對(duì)象應(yīng)當(dāng)對(duì)其他對(duì)象有盡可能少的了解,不和陌生人說(shuō)話(huà)。英文簡(jiǎn)寫(xiě)為: LoD.
類(lèi)的設(shè)計(jì)接口盡量封裝完善,讓外部直接調(diào)用
#include#include #include using namespace std; class AbstractBuilding { public: virtual void sale() = 0; virtual string getQuality() = 0; }; class BuildingA :public AbstractBuilding { public: BuildingA() { mQulity = "高品質(zhì)"; } virtual void sale() { cout << "樓盤(pán)A" << mQulity << "被售賣(mài)!" << endl; } virtual string getQuality() { return mQulity; } public: string mQulity; }; class BuildingB :public AbstractBuilding { public: BuildingB() { mQulity = "低品質(zhì)"; } virtual void sale() { cout << "樓盤(pán)B" << mQulity << "被售賣(mài)!" << endl; } virtual string getQuality() { return mQulity; } public: string mQulity; }; // 中介類(lèi) class Mediator { public: Mediator() { AbstractBuilding* building = new BuildingA; vBuilding.push_back(building); building = new BuildingB; vBuilding.push_back(building); } // 對(duì)外提供接口 AbstractBuilding* findMyBuilding(string quality) { for (vector ::iterator it = vBuilding.begin(); it != vBuilding.end(); it++) { if ((*it)->getQuality() == quality) { return *it; } } return NULL; } ~Mediator() { for (vector ::iterator it = vBuilding.begin(); it != vBuilding.end(); it++) { if (*it != NULL) delete *it; } } public: vector vBuilding; }; void test01() { Mediator* mediator = new Mediator; AbstractBuilding* building = mediator->findMyBuilding("低品質(zhì)"); if (building != NULL) { building->sale(); } else { cout << "沒(méi)有符號(hào)條件的樓盤(pán)" << endl; } } int main() { test01(); system("pause"); }
關(guān)于“C++設(shè)計(jì)模式迪米特法則的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。