面向对象设计(OOD)的SOLID 原则
SOLID 原则是面向对象设计(OOD)中的一组核心概念,旨在促进软件的可维护性、灵活性和可扩展性。下面为每个原则提供一个简单的代码示例来阐明其意义和应用方式。
S:单一职责原则(Single Responsibility Principle)
单一职责原则指一类应该只有一个改变的理由,即该类只负责一件事。
示例:一个日志记录类,仅负责日志记录功能。
class Logger:
def log(self, message):
print(f"Log message: {message}")
# 使用
logger = Logger()
logger.log("This is a log message.")
O:开闭原则(Open/Closed Principle)
开闭原则是指软件参与活动扩展开放,对修改关闭。这意味着应该能够增加功能而修改现有代码。
示例:使用抽象基类来允许添加新功能而不修改现有代码。
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# 使用
shapes = [Rectangle(3, 4), Circle(5)]
for shape in shapes:
print(shape.area())
L: 里氏替换原则 (Liskov Substitution Principle)
里氏替换原则指子类应能够替换其基类而不影响程序的功能。
示例:确保子类完全实现父类的方法。
class Bird:
def fly(self):
print("The bird is flying")
class Duck(Bird):
def fly(self):
print("The duck is flying")
class Ostrich(Bird):
def fly(self):
raise Exception("Ostriches cannot fly")
# 使用
birds = [Duck(), Ostrich()]
for bird in birds:
try:
bird.fly()
except Exception as e:
print(e)
I:接口隔离原则(Interface Segregation Principle)
接口隔离原则指不得强迫客户依赖于它们不使用的接口。
示例:使用专用的接口而不是一个大而全的接口。
class Printer:
def print_document(self, document):
print("Printing document:", document)
class Stapler:
def staple_document(self, document):
print("Stapling document:", document)
class Photocopier(Printer, Stapler):
pass
# 使用
photocopier = Photocopier()
photocopier.print_document("Document1")
photocopier.staple_document("Document1")
D:依赖倒置原则(Dependency Inversion Principle)
依赖倒置原则是指高层模块不应依赖于低层模块,两者都应依赖于抽象;抽象不应依赖于细节,细节应依赖于抽象。
示例:使用抽象类来定义依赖关系,而不是具体类。
from abc import ABC, abstractmethod
class Button(ABC):
@abstractmethod
def on_press(self):
pass
class Light:
def turn_on(self):
print("The light is on")
class LightSwitch(Button):
def __init__(self, light):
self.light = light
def on_press(self):
self.light.turn_on()
# 使用
light = Light()
switch = LightSwitch(light)
switch.on_press()
作者:兔老大RabbitMQ