SOLID 原則 - paulip114/blog GitHub Wiki

什麽是 SOLID 原則?

SOLID 原則是一組軟體設計原則,用於指導軟體開發人員設計和實現高品質、易於維護和擴展的軟體。

S = Single-responsibility principle (SRP) = 單一責任原則

O = Open-close principle (OCP) = 開放封閉原則

L = Liskov substitution principle (LSP) = 里氏替換原則

I = Interface segregation principle (ISP) = 介面隔離原則

D = Dependency inversion principle (DIP) = 依賴反轉原則

S+O+L + I + D = SOLID

Single-responsibility principle (SRP) 單一責任原則

  • A class should have only one reason to change
// Demo code in C#
public class FeeCalculator
{
    public decimal CalcTax(decimal amount)
    {
        // Implement tax calculation logic here
        // For example, let's assume a 10% tax rate
        return amount * 0.10m;
    }

    public decimal CalcCreditCardFee(decimal amount)
    {
        // Implement credit card fee calculation logic here
        // For example, let's assume a 2% fee
        return amount * 0.02m;
    }
}

Open-close principle (OCP) 開放封閉原則

  • You should be able to extend the behavior of a system without having to modify the system

Liskov substitution principle (LSP) 里氏替換原則

  • Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

Interface segregation principle (ISP) 介面隔離原則

  • No code should be forced to depend on methods it does not use.

Dependency inversion principle (DIP) 依賴反轉原則

  • High level modules should not depend on low level modules; both should depend on abstractions.