今天來簡介程式開發裡 SOLID 原則的單一職責、開放/封閉原則,並用 C# 實作。
一個類別負責一件工作。
// 負責計算
public class Order
{
public int OrderId { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public double CalculateTotalPrice(double unitPrice)
{
return unitPrice * Quantity;
}
}
// 負責印出資料
public class OrderPrinter
{
public void PrintOrderDetails(Order order)
{
Console.WriteLine($"Order ID: {order.OrderId}");
Console.WriteLine($"Product Name: {order.ProductName}");
Console.WriteLine($"Quantity: {order.Quantity}");
}
}
可以開放擴充新功能,且盡可能減少對現有程式碼的修改。
// 一開始先設計好可擴充的類別
public abstract class Discount
{
public abstract double ApplyDiscount(double price);
}
// 沒有折扣
public class NoDiscount : Discount
{
public override double ApplyDiscount(double price)
{
return price; // 傳回原價
}
}
// 有折扣
public class PercentageDiscount : Discount
{
private double percentage;
public PercentageDiscount(double percentage)
{
this.percentage = percentage;
}
public override double ApplyDiscount(double price)
{
return price - (price * percentage / 100);
}
}
// 擴充後可以不修改現有類別
public class OrderWithDiscount
{
public double CalculatePrice(double price, Discount discount)
{
return discount.ApplyDiscount(price);
}
}
用以下的程式呼叫上述類別:
public class Program
{
public static void Main()
{
// 單一職責原則
Order order = new Order { OrderId = 1, ProductName = "Laptop", Quantity = 2 };
OrderPrinter printer = new OrderPrinter();
printer.PrintOrderDetails(order);
// 開放/封閉原則
Discount discount = new PercentageDiscount(10);
OrderWithDiscount orderWithDiscount = new OrderWithDiscount();
Console.WriteLine($"Price after discount: {orderWithDiscount.CalculatePrice(1000, discount)}");
Console.WriteLine($"Price after discount: {orderWithDiscount.CalculatePrice(1000, noDiscount)}");
}
}
當程式變得需要時常修改時,上述原則讓程式更容易擴充,且減少雜亂的程度。