SOLID 原則是一組設計原則,可協助開發人員創建更具可維護性和可擴充性的軟體。讓我們用簡短的 Python 範例來分解每個原則。
一個類別應該只有一個改變的理由,這意味著它應該只有一項工作或責任。
class Invoice: def __init__(self, items): self.items = items def calculate_total(self): return sum(item['price'] for item in self.items) class InvoicePrinter: def print_invoice(self, invoice): for item in invoice.items: print(f"{item['name']}: ${item['price']}") print(f"Total: ${invoice.calculate_total()}") # Usage invoice = Invoice([{'name': 'Book', 'price': 10}, {'name': 'Pen', 'price': 2}]) printer = InvoicePrinter() printer.print_invoice(invoice)
軟體實體應該對擴充開放,但對修改關閉。
class Discount: def apply(self, amount): return amount class TenPercentDiscount(Discount): def apply(self, amount): return amount * 0.9 # Usage discount = TenPercentDiscount() print(discount.apply(100)) # Output: 90.0
超類別的物件應該可以替換為子類別的對象,而不影響程式的正確性。
class Bird: def fly(self): return "Flying" class Sparrow(Bird): pass class Ostrich(Bird): def fly(self): return "Can't fly" # Usage def make_bird_fly(bird: Bird): print(bird.fly()) sparrow = Sparrow() ostrich = Ostrich() make_bird_fly(sparrow) # Output: Flying make_bird_fly(ostrich) # Output: Can't fly
不應強迫客戶端依賴他們不使用的介面。
class Printer: def print(self, document): pass class Scanner: def scan(self, document): pass class MultiFunctionPrinter(Printer, Scanner): def print(self, document): print(f"Printing: {document}") def scan(self, document): print(f"Scanning: {document}") # Usage mfp = MultiFunctionPrinter() mfp.print("Document1") mfp.scan("Document2")
高層模組不應該依賴低層模組。兩者都應該依賴抽象。
class Database: def connect(self): pass class MySQLDatabase(Database): def connect(self): print("Connecting to MySQL") class Application: def __init__(self, db: Database): self.db = db def start(self): self.db.connect() # Usage db = MySQLDatabase() app = Application(db) app.start() # Output: Connecting to MySQL
這些範例使用 Python 以簡潔的方式說明了 SOLID 原則。每個原則都有助於建立健壯、可擴展且可維護的程式碼庫。
以上是透過 Python 範例了解 SOLID 原則的詳細內容。更多資訊請關注PHP中文網其他相關文章!