軟件設計原則及設計模式

一. 軟件六大設計原則(SOLID)

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

把這六個原則的首字母聯合起來(兩個 L 算做一個)就是 SOLID (solid,穩定的),其代表的含義就是這六個原則結合使用的好處:建立穩定、靈活、健壯的設計。下面我們來分別看一下這六大設計原則。

1.1 單一職責原則(Single Responsibility Principle

一個類應該只有一個發生變化的原因

There should never be more than one reason for a class to change.

1.2 開閉原則(Open Closed Principle)

一個軟件實體,如類、模塊和函數應該對擴展開放,對修改關閉

Software entities like classes, modules and functions should be open for extension but closed for modification

1.3 里氏替換原則(Liskov Substitution Principle)

所有引用基類的地方必須能透明地使用其子類的對象

Functions that use use pointers or references to base classes must be able to use objects of derived classes without knowing it.

1.4 迪米特法則(Law of Demeter)

只與你的直接朋友交談,不跟“陌生人”說話

Talk only to your immediate friends and not to strangers

其含義是:如果兩個軟件實體無須直接通信,那麼就不應當發生直接的相互調用,可以通過第三方轉發該調用。其目的是降低類之間的耦合度,提高模塊的相對獨立性。

1.5 接口隔離原則(Interface Segregation Principle)

  • 客戶端不應該依賴它不需要的接口。
  • 類間的依賴關係應該建立在最小的接口上。

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.

注:該原則中的接口,是一個泛泛而言的接口,不僅僅指具體的接口,還包括其中的抽象類。

1.6 依賴倒置原則(Dependence Inversion Principle)

  • 上層模塊不應該依賴底層模塊,它們都應該依賴於抽象。
  • 抽象不應該依賴於細節,細節應該依賴於抽象。

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.

二. 軟件設計23種模式

2.1 GOF(四人幫,全拼 Gang of Four)

在 1994 年,由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides 四人合著出版了一本名爲 Design Patterns - Elements of Reusable Object-Oriented Software(中文譯名:設計模式 - 可複用的面向對象軟件元素) 的書,該書首次提到了軟件開發中設計模式的概念。

四位作者合稱 GOF(四人幫,全拼 Gang of Four)。他們所提出的設計模式主要是基於以下的面向對象設計原則。

  • 對接口編程而不是對實現編程。
  • 優先使用對象組合而不是繼承。

2.3 設計模式的類型

在Design Patterns - Elements of Reusable Object-Oriented Software(中文譯名:設計模式 - 可複用的面向對象軟件元素) 中所提到的,總共有 23 種設計模式。這些模式可以分爲三大類:創建型模式(Creational Patterns)、結構型模式(Structural Patterns)、行爲型模式(Behavioral Patterns)。

創建型模式

這些設計模式提供了一種在創建對象的同時隱藏創建邏輯的方式,而不是使用 new 運算符直接實例化對象。這使得程序在判斷針對某個給定實例需要創建哪些對象時更加靈活。

結構型模式

這些設計模式關注類和對象的組合。繼承的概念被用來組合接口和定義組合對象獲得新功能的方式。

行爲型模式

這些設計模式特別關注對象之間的通信。

參考:
https://www.runoob.com/design-pattern/design-pattern-intro.html
https://www.jianshu.com/p/3268264ae581

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