🔥《ChatGPT 指令大全與創新應用》新書上架！👉 立即購買

# 什麼是 SOLID 原則？

## 什麼是 SOLID 原則？

SOLID 原則是一組軟體設計原則，用於指導軟體開發人員設計和實現高質量的、易於維護和擴展的軟體。它是由羅伯特·C·馬丁在其著作《Agile Software Development, Principles, Patterns, and Practices》中提出的，是目前軟體工程界被廣泛接受的一種軟體設計理念。

## SOLID 五個原則

SOLID 原則包括以下五個原則：

1. 單一職責原則（Single Responsibility Principle，SRP）

class ShoppingCart:
def __init__(self):
self.items = []
self.total = 0

self.items.append(item)
self.total += item.price

def remove_item(self, item):
self.items.remove(item)
self.total -= item.price

def print_receipt(self):
print('Items:')
for item in self.items:
print(f'{item.name} - ${item.price}') print(f'Total:${self.total}')


1. 開放封閉原則（Open-Closed Principle，OCP）

class ShoppingCart:
def __init__(self):
self.items = []

self.items.append(item)

def remove_item(self, item):
self.items.remove(item)

def get_total_price(self):
total_price = 0
for item in self.items:
total_price += item.price

class DiscountedShoppingCart(ShoppingCart):
def get_total_price(self):
total_price = super().get_total_price()


class ShoppingCart:
def __init__(self):
self.items = []

self.items.append(item)

def remove_item(self, item):
self.items.remove(item)

def get_total_price(self):
total_price = 0
for item in self.items:
total_price += item.price

class Discount:
def calculate_discount(self, total_price):

class TenPercentDiscount(Discount):
def calculate_discount(self, total_price):

class ShoppingCartWithDiscount:
def __init__(self, discount: Discount):
self.items = []
self.discount = discount

self.items.append(item)

def remove_item(self, item):
self.items.remove(item)

def get_total_price(self):
total_price = 0
for item in self.items:
total_price += item.price
return self.discount.calculate_discount(total_price)


1. 里氏替換原則（Liskov Substitution Principle，LSP）

class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

def set_width(self, width):
self.width = width

def set_height(self, height):
self.height = height

def area(self):
return self.width * self.height

class Square(Rectangle):
def __init__(self, size):
self.width = size
self.height = size

def set_width(self, width):
self.width = width
self.height = width

def set_height(self, height):
self.width = height
self.height = height

square = Square(5)
square.set_width(10)
square.set_height(5)
print(square.area())


class Shape:
def area(self):
pass

class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

def set_width(self, width):
self.width = width

def set_height(self, height):
self.height = height

def area(self):
return self.width * self.height

class Square(Shape):
def __init__(self, size):
self.size = size

def set_size(self, size):
self.size = size

def area(self):
return self.size ** 2

def print_area(shape):
print(f"Area: {shape.area()}")

shapes = [Rectangle(5, 10), Square(5)]
for shape in shapes:
print_area(shape)


1. 介面隔離原則（Interface Segregation Principle，ISP）

class Machine:
def print(self, document):
pass

def fax(self, document):
pass

def scan(self, document):
pass

class MultiFunctionPrinter(Machine):
def print(self, document):
print("Printing")

def fax(self, document):
print("Faxing")

def scan(self, document):
print("Scanning")


class Printer:
def print(self, document):
pass

class Fax:
def fax(self, document):
pass

class Scanner:
def scan(self, document):
pass

class MultiFunctionDevice(Printer, Fax, Scanner):
def print(self, document):
print("Printing")

def fax(self, document):
print("Faxing")

def scan(self, document):
print("Scanning")


1. 依賴反轉原則（Dependency Inversion Principle，DIP）

class Logger:
def log(self, message):
print(f"Log: {message}")

class UserService:
def __init__(self):
self.logger = Logger()

try:
# register user to database
except Exception as e:
print(f"Error: {e}")
self.logger.log(f"Error: {e}")


from abc import ABC, abstractmethod

class Logger(ABC):
@abstractmethod
def log(self, message):
pass

class ConsoleLogger(Logger):
def log(self, message):
print(f"Log: {message}")

class UserService:
def __init__(self, logger: Logger):
self.logger = logger

try:
# register user to database
except Exception as e:
print(f"Error: {e}")
self.logger.log(f"Error: {e}")

logger = ConsoleLogger()
service = UserService(logger)


💡 何謂高層次模組、何謂低層次模組？ 在軟體系統中，我們常會區分系統的不同層次，例如資料存取層、商業邏輯層、介面層等，資料存取層可能包含了一些和資料庫溝通的程式碼，而商業邏輯層則使用資料存取層中提供的方法來操作資料。在這種情況下，商業邏輯層可以被視為高層次模組，因為它使用了低層次模組的服務。

ExplainThis