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中文网其他相关文章!