AdSense

網頁

2019/8/16

Java 物件導向程式設計原則 SOLID Design Principles

在物件導向程式程式設計中,有五個應遵循的設計原則,通稱為SOLID設計原則。

SOLID設計原則分別為以下原則,取英文首字組成。

  • Single Responsibility Principle (SRP) 單一職責原則
  • Open/Closed Principle (OCP) 開放封閉原則
  • Liskov Substitution Principle (LSP) 里氏替換原則
  • Interface Segregation Principle (ISP) 介面隔立原則
  • Dependency Inversion Principle (DIP) 依賴反轉原則


單一職責原則 Single Responsibility Principle (SRP)

一個類別應該只有單一職責,一處改變只能影響一個類別。

A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class


開放封閉原則 Open/Closed Principle (OCP)

物件或實體應該對擴展開放,但對修改封閉。

Objects or entities should be open for extension but closed for modification.


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

令T類的物件x對Φ(x)為可證,S為T的子類則S類的物件y對Φ(y)也應為可證。

Let Φ(x) be a property provable about objects of x of type T. Then Φ(y) should be provable for objects y of type S where S is a subtype of T.

大部分的人都看不懂上面在講什麼,其意思為「程式中所有父類物件都可由子類物件替代且行為不變」。


介面隔立原則 Interface Segregation Principle (ISP)

客戶端不應被迫實作不使用的介面,或是說客戶端不應被迫依賴不使用的方法。

A client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.


依賴反轉原則 Dependency Inversion Principle

實體必須依賴抽象而非具體。高階模組不能依賴低階模組,而應依賴抽象。

Entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.


在物件導向程式中使用SOLID原則來設計程式元件可提高程式的可讀性,可維護性,可擴充性,可測試性等。

也就是說遵從SOLID原則來設計程式可讓程式比較好閱讀,修改容易,不會改了一個地方其他地方壞掉,或是不用改一堆地方,並且在原有的程式碼插入新的功能很輕鬆,減少重複的程式碼,撰寫測試程式不會修改到主程式等。


  • 無瑕的程式碼 - 整潔的軟體設計與架構篇 - Robert C. Martin (ISBN 978-986-434-294-5)

沒有留言:

AdSense