您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關C++設計模式迪米特法則的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
迪米特法則(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"); }
關于“C++設計模式迪米特法則的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。