博客地址已更改,文章數量較多不便批量修改,若想訪問源文請到 coologic博客 查閱,網址:www.coologic.cn
如本文記錄地址為 techieliang.com/A/B/C/ 請改為 www.coologic.cn/A/B/C/ 即可查閱
版權聲明:若無來源注明, Techie亮博客文章均為原創。 轉載請以鏈接形式標明本文標題和地址:
本文標題:C++設計模式 本文地址: http://techieliang.com/2017/12/764/
最近開始看設計模式之禪,之前看過一遍可惜沒有學以致用,這次邊看邊整理
1. 六大設計原則
1.1. 單一職責原則(Single Responsibility Principle)
There should never be more than one reason for a class to change. 應該有且僅有一個原因引起類的變更 。
1.2. 里氏替換原則(Liskov Substitution Principle, LSP)
第一種定義, 也是最正宗的定義: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T,the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T.(如果對每一個類型為S的對象o1, 都有類型為T的對象o2, 使得以T定義的所有程序P在所有的對象o1都代換成o2時, 程序P的行為沒有發生變化, 那么類型S是類型T的子類型。 )
第二種定義: Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.(所有引用基類的地方必須能透明地使用其子類的對象。 )
1.3. 依賴倒置原則(Dependence Inversion Principle, DIP)
High level modules should not depend upon low level modules.Both should depend upon abstractions.Abstractions should not depend upon details.Details should depend upon abstractions.
高層模塊不應該依賴低層模塊,兩者都應該依賴其抽象;抽象不應該依賴細節;細節應該依賴抽象。
依賴關系有三種方式來傳遞: 構造函數傳遞依賴對象 、 Setter方法傳遞依賴對象 、 接口聲明依賴對象。
1.4. 接口隔離原則
實例接口(Object Interface)類的對象符合類的定義
類接口(Class Interface)類的定義符合接口定義 ,c++中是符合virtual關鍵詞定義的虛函數,java中符合interface關鍵詞定義的接口
- Clients should not be forced to depend upon interfaces that they don’t use.(客戶端不應該依賴它不需要的接口。 )
- The dependency of one class to another one should depend on the smallest possible interface.(類間的依賴關系應該建立在最小的接口上。 )
1.5. 迪米特法則(Law of Demeter, LoD)
也稱為最少知識原則(Least Knowledge Principle, LKP) , 一個對象應該對其他對象有最少的了解。
- Only talk to your immediate friends(只與直接的朋友通信。 )
- 朋友間也是有距離的, 盡量不要對外公布太多的public方法和非靜態的public變量, 盡量內斂, 多使用private、 package-private、 protected等訪問權限
- 是自己的就是自己的, 如果一個方法放在本類中, 既不增加類間關系, 也對本類不產生負面影響, 那就放置在本類中
- 謹慎使用Serializable
1.6. 開閉原則
Software entities like classes,modules and functions should be open for extension but closed for modifications.(一個軟件實體如類、 模塊和函數應該對擴展開放, 對修改關閉。 )
2. 設計模式分類
共有 23 種設計模式可分為三大類
類型 | 簡述 |
---|---|
創建型模式(Creational Patterns) | 處理對象的創建機制,試圖在一個適合的方式創建對象,隱藏了創造過程的邏輯不需要使用new。wiki |
結構型模式(Structural Patterns) | 通過描述實體間關系、類和對象的組合來簡化設計。wiki |
行為型模式(Behavioral Patterns) | 確定對象之間的公共通信模式並實現這些模式的設計模式。通過這樣做,這些模式增加了執行此通信的靈活性。wiki |
2.1. 創建型模式
- 單例模式(Singleton Pattern)
Ensure a class has only one instance, and provide a global point of access to it.(確保某一個類只有一個實例, 而且自行實例化並向整個系統提供這個實例。) - 工廠方法模式 (Factory Method Pattern)
Define an interface for creating an object,but let subclasses decide which class to instantiate.Factory Method lets a class defer instantiation to subclasses.(定義一個用於創建對象的接口, 讓子類決定實例化哪一個類。 工廠方法使一個類的實例化延遲到其子類。 ) - 抽象工廠模式 (Abstract Factory Pattern)
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.(為創建一組相關或相互依賴的對象提供一個接口, 而且無須指定它們的具體類。 ) - 建造者模式/ 生成器模式(Builder Pattern)
Separate the construction of a complex object from its representation so that the same construction process can create different representations.(將一個復雜對象的構建與它的表示分離, 使得同樣的構建過程可以創建不同的表示。 ) - 原型模式(Prototype Pattern)
Specify the kinds of objects to create using a prototypical instance,and create new objects by copying this prototype.(用原型實例指定創建對象的種類, 並且通過拷貝這些原型創建新的對象。 )
2.2. 機構型模式
- 代理模式(Proxy Pattern)
Provide a surrogate or placeholder for another object to control access to it.(為其他對象提供一種代理以控制對這個對象的訪問。 ) - 裝飾模式(Decorator Pattern)
Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible
alternative to subclassing for extending functionality.(動態地給一個對象添加一些額外的職責。就增加功能來說, 裝飾模式相比生成子類更為靈活。 ) - 適配器模式/變壓器模式(Adapter Pattern)/ 包裝模式(Wrapper)
包裝模式也包括裝飾模式
Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.(將一個類的接口變換成客戶端所期待的另一種接口, 從而使原本因接口不匹配而無法在一起工作的兩個類能夠在一起工作。 ) - 組合模式/合成模式(Composite Pattern)/ 部分–整體模式(Part-Whole)
Compose objects into tree structures to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of objects uniformly.(將對象組合成樹形結構以表示“部分–整體”的層次結構, 使得用戶對單個對象和組合對象的使用具有一致性。 ) - 外觀模式/ 門面模式(Facade Pattern)
Provide a unified interface to a set of interfaces in a subsystem.Facade defines a higher-level interface that makes the subsystem easier to use.(要求一個子系統的外部與其內部的通信必須通過一個統一的對象進行。 門面模式提供一個高層次的接口, 使得子系統更易於使用。 ) - 享元模式(Flyweight Pattern)
池技術的重要實現方式。 Use sharing to support large numbers of fine-grained objects efficiently.(使用共享對象可有效地支持大量的細粒度的對象。 ) - 橋梁模式/橋接模式(Bridge Pattern)
Decouple an abstraction from its implementation so that the two can vary independently.(將抽象和實現解耦, 使得兩者可以獨立地變化。 )
2.3. 行為型模式
- 模版方法模式(Template Method Pattern)
Define the skeleton of an algorithm in an operation,deferring some steps to subclasses.Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.(定義一個操作中的算法的框架, 而將一些步驟延遲到子類中。 使得子類可以不改變一個算法的結構即可重定義該算法的某些特定步驟。 ) - 命令模式(Command Pattern)
Encapsulate a request as an object,thereby letting you parameterize clients with different requests,queue or log requests,and support undoable
operations.(將一個請求封裝成一個對象, 從而讓你使用不同的請求把客戶端參數化, 對請求排隊或者記錄請求日志, 可以提供命令的撤銷和恢復功能。 ) - 中介者模式(Mediator Pattern)
Define an object that encapsulates how a set of objects interact.Mediator promotes loose coupling by keeping objects from referring to each other
explicitly,and it lets you vary their interaction independently.(用一個中介對象封裝一系列的對象交互, 中介者使各對象不需要顯示地相互作用, 從而使其耦合松散, 而且可以獨立地改變它們之間的交互。 ) - 職責鏈模式 / 責任鏈模式(Chain of Responsibility Pattern)
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.Chain the receiving objects and pass the request along the chain until an object handles it.(使多個對象都有機會處理請求, 從而避免了請求的發送者和接受者之間的耦合關系。 將這些對象連成一條鏈, 並沿着這條鏈傳遞該請求, 直到有對象處理它為止。 ) - 策略模式/政策模式(Strategy Pattern)
Define a family of algorithms,encapsulate each one,and make them interchangeable.(定義一組算法, 將每個算法都封裝起來, 並且使它們之間可以互換。 ) - 迭代器模式(Iterator Pattern)
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.(它提供一種方法訪問一個容器對象中各個元素, 而又不需暴露該對象的內部細節。 ) - 觀察者模式(Observer Pattern)/發布訂閱模式(Publish/subscribe)
Define a one-to-many dependency between objects so that when one object changes state,all its dependents are notified and updated automatically.(定義對象間一種一對多的依賴關系, 使得每當一個對象改變狀態, 則所有依賴於它的對象都會得到通知並被自動更新。 ) - 備忘錄模式(Memento Pattern)
Without violating encapsulation,capture and externalize an object’s internal state so that the object can be restored to this state later.(在不破壞封裝性的前提下, 捕獲一個對象的內部狀態, 並在該對象之外保存這個狀態。 這樣以后就可將該對象恢復到原先保存的狀態。 ) - 訪問者模式(Visitor Pattern)
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. (封裝一些作用於某種數據結構中的各元素的操作, 它可以在不改變數據結構的前提下定義作用於這些元素的新的
操作。 ) - 狀態模式(State Pattern)
Allow an object to alter its behavior when its internal state changes.The object will appear to change its class.(當一個對象內在狀態改變時允許其改變行為, 這個對象看起來像改變了其類。 ) - 解釋器模式(Interpreter Pattern)
Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.(給定一門語言, 定義它的文法的一種表示, 並定義一個解釋器, 該解釋器使用該表示來解釋語言中的句子。 )
3. 范例源碼
源碼GitHub:CppDesignPattern