六大設計原則

六大原則:

Single Responsibility Principle:單一職責原則
Open Closed Principle:開閉原則
Liskov Substitution Principle:里氏替換原則
Law of Demeter:迪米特法則
Interface Segregation Principle: 接口隔離原則
Dependence Inversion Principle: 依賴倒置原則

單一職責原則:Single Responsibility Principle,簡稱SRP。

定義:
There should never be more than one reason for a class to change.
應該有且僅有一個原因引起類的變更。

好處:
類的複雜性降低,實現什麼職責都有清晰明確的定義
可讀性與可維護性提高
變更引起的風險降低。

壞外,無清晰明確的職責定義,過分細分職責會造成類數量劇增,人爲的增加維護難度和系統複雜性。

對於單一職責原則,類的設計應儘量做到只有一個原因引起變化。

里氏替換原則:Liskov Substitution Principle,簡稱LSP。

定義:
If for each object 01 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時,程序的行爲沒有發生變化,那麼類型S是類型T的子類型。

Functions that use ponters or references to base classes must be able to use objects of derived classes without knowing it .
所有引用基類的地方必須能透明的使用其子類對象。即父類能出現的地方子類就能出現,而且替換爲子類也不會產生任何錯誤或異常。

里氏替換原則目的爲增加程序的健壯性,版本升級時也可以保持非常好的兼容性。即使增加子類,原有的子類還可以繼續運行。在實際項目中,每個子類對應不同的業務含義
,使用父類作爲參數,傳遞不同的子類完成不同的業務邏輯,非常完美。

依賴倒置原則: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.

高層模塊不應該依賴低層模塊,兩者都應該依賴其抽象。

抽象不應該依賴細節。

細節應該依賴抽象。

核心爲面向接口編程。

接口隔離原則:

Cilents 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.
類間的依賴關係應該建立在最小的接口上

其核心爲儘可能的小。

迪米特法則:Law of Demeter,LoD),也稱最少知識原則:Least Knowledge Principle,LKP.
一個對象應該對其他對象有最少的瞭解。或者說一個類應該對自己需要耦合或調用的類知道的最少。

還有一個英文解釋:Only talk to your immedate friends(只與直接朋友通信)

直接朋友:類直接依賴、聚合、組合的類

一個方法中儘量不要出現類中不存在的對象,JDK提供的類除外。

開閉原則:
Software entities like classes, modules and functions should be open for extension but closed for modifications.
一個軟件實體如類、模塊和函數應該對擴展開放,對修改關閉。

開閉原則即爲告訴我們應儘量通過擴展軟件實體的行爲來實現變化,而不是通過修改已有代碼來完成變化,它是軟件實體的未來事件而制定的對現行開發設計進行
約束的一個原則。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章