淺談C++ 設(shè)計模式的基本原則
先上銀行類案例代碼如下:
#include<iostream> using namespace std; class BankWorker { public: void save() { cout << "存款" << endl; } void moveM() { cout << "取款" << endl; } void jiaofei() { cout << "繳費" << endl; } }; class AbBankWorker { public: virtual void dothing() = 0; }; class SaveBanker :public AbBankWorker { public: virtual void dothing() { cout << "存款" << endl; } }; class MoveBanker :public AbBankWorker { public: virtual void dothing() { cout << "取款" << endl; } }; class SaveBanker :public AbBankWorker { public: virtual void dothing() { cout << "繳費款" << endl; } }; void main11() { BankWorker*bw = new BankWorker; bw->jiaofei(); bw->moveM(); bw->save(); cout << "hello..." << endl; system("pause"); return; } void main22() { AbBankWorker*bw = NULL; bw=new MoveBanker; bw->dothing(); delete bw; return; } void main() { main22(); system("pause"); return; }
單一職責原則類的職責要單一,對外只提供一種功能,而引起內(nèi)變化的原因都應(yīng)該只有一個,就是依賴倒置原則依賴于抽象接口,不要依賴具體的實現(xiàn)類,也就是針對接口編程
#include<iostream> using namespace std; class HardDisk {public: virtual void work(); }; class Memory { public: virtual void work(); }; class Cpu { public: virtual void work(); }; class ComPuter { public: ComPuter(HardDisk*m_handdisk, Memory*m_memory, Cpu*m_cpu) { m_handdisk = handdisk; m_memory = memory; m_cpu = cpu; } public: void work() { m_handdisk->work(); m_memory->work(); m_cpu->work(); } private: HardDisk*m_handdisk; Memory*m_memory; Cpu*m_cpu; }; class InterCpu :public Cpu { public: void work() { cout << "我是因特爾廠家" << endl; } }; class XSDisk :public HardDisk { public: void work() { cout << "我是西數(shù)硬盤廠家" << endl; } }; class JSDMem :public Memory { public: void work() { cout << "我是JSDMem廠家" << endl; } }; void main() { HardDisk*handdisk=NULL; Memory*memory=NULL; Cpu*cpu=NULL; handdisk = new XSDisk; memory= new JSDMem; cpu = new InterCpu; ComPuter*mycomputer = new ComPuter(harddisk, memory, cpu); mycomputer->work(); delete mycomputer; delete cpu; delete memory; delete harddisk; cout << "hello" << endl; system("pause"); return; }
接口隔離原則不應(yīng)該強迫客戶的程序依賴他們不需要的接口方法,一個接口應(yīng)該是提供一種對外功能,不應(yīng)該把所有的操作都封裝到一個接口中去
里氏替換原則任何抽象類出現(xiàn)的地方都可以用它的實現(xiàn)類進行替換,實際就是虛擬機智語言級別,實現(xiàn)面向?qū)ο蠊δ?/p>
優(yōu)先使用組合而不是繼承原則如果使用繼承,會導致復位的任何變化,都可能影響此類的行為,如果使用對象組合,就降低了這種依賴關(guān)系
迪米特法則一個對象應(yīng)當對其他對象盡可能少的了解,從而降低各個對象之間的耦合,提高系統(tǒng)的可維護性。例如,在一個程序中,各個模塊之間相互調(diào)用時,通常會提供一個統(tǒng)一的接口來實現(xiàn),這樣其他模塊不需要了解另外一個模塊的內(nèi)部實現(xiàn)細節(jié),這樣當一個模塊內(nèi)部的實現(xiàn)發(fā)生改變的時候,不會影響其他模塊的使用黑盒原理。
到此這篇關(guān)于淺談C++ 設(shè)計模式的基本原則的文章就介紹到這了,更多相關(guān)C++ 設(shè)計模式的基本原則內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
DSP中浮點轉(zhuǎn)定點運算--定點數(shù)模擬浮點數(shù)運算及常見的策略
本文主要講解DSP中定點數(shù)模擬浮點數(shù)運算及常見的策略,具有參考價值,需要的朋友可以參考一下。2016-06-06Opencv 視頻轉(zhuǎn)為圖像序列的實現(xiàn)
今天小編就為大家分享一篇Opencv 視頻轉(zhuǎn)為圖像序列的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12C語言?模擬實現(xiàn)memcpy與memmove函數(shù)詳解
這篇文章主要介紹了C語言詳解如何模擬內(nèi)存函數(shù),用到了mencpy與memmove兩個函數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2022-04-04