代码解读复制代码# DRY (Don't Repeat Yourself) 原则示例
# 违反DRY原则的代码
def get_area_circle(radius):
return 3.14 * radius * radius
def get_area_cylinder(radius, height):
return 2 * 3.14 * radius * height + 2 * 3.14 * radius * radius
# 遵循DRY原则的代码
import math
def get_circle_area(radius):
return math.pi * radius ** 2
def get_cylinder_area(radius, height):
circle_area = get_circle_area(radius)
return 2 * math.pi * radius * height + 2 * circle_area
代码解读复制代码# 违反KISS原则的代码
def is_even(num):
if num % 2 == 0:
return True
else:
return False
# 遵循KISS原则的代码
def is_even(num):
return num % 2 == 0
SOLID 是面向对象编程和设计的五个基本原则的首字母缩写:
S - 单一职责原则 (Single Responsibility Principle)
O - 开放封闭原则 (Open-Closed Principle)
L - 里氏替换原则 (Liskov Substitution Principle)
I - 接口隔离原则 (Interface Segregation Principle)
D - 依赖倒置原则 (Dependency Inversion Principle)
代码解读复制代码
# 单一职责原则 (SRP)
class Report:
def generate_report(self, data):
# 生成报告逻辑
pass
class ReportPrinter:
def print_report(self, report):
# 打印报告逻辑
pass
# 开放封闭原则 (OCP)
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 math.pi * self.radius ** 2
# 里氏替换原则 (LSP)
class Bird:
def fly(self):
pass
class Sparrow(Bird):
def fly(self):
print("Sparrow flying")
class Ostrich(Bird):
def fly(self):
raise NotImplementedError("Ostriches can't fly")
# 更好的设计
class Bird:
pass
class FlyingBird(Bird):
def fly(self):
pass
class Sparrow(FlyingBird):
def fly(self):
print("Sparrow flying")
class Ostrich(Bird):
pass
# 接口隔离原则 (ISP)
from abc import ABC, abstractmethod
class Printer(ABC):
@abstractmethod
def print(self, document):
pass
class Scanner(ABC):
@abstractmethod
def scan(self, document):
pass
class ModernPrinter(Printer, Scanner):
def print(self, document):
print("Printing:", document)
def scan(self, document):
print("Scanning:", document)
# 依赖倒置原则 (DIP)
class LightBulb:
def turn_on(self):
print("LightBulb: turned on")
def turn_off(self):
print("LightBulb: turned off")
class ElectricPowerSwitch:
def __init__(self, device):
self.device = device
self.on = False
def press(self):
if self.on:
self.device.turn_off()
self.on = False
else:
self.device.turn_on()
self.on = True
# 使用
bulb = LightBulb()
switch = ElectricPowerSwitch(bulb)
switch.press()
switch.press()
遵循这些原则可以帮助开发者创建更加健壮、灵活和可维护的软件系统。
这些原则是软件开发中的重要指导方针,它们帮助开发者创建高质量的代码和系统架构。简要总结一下每个原则的核心思想:
这些原则不是硬性规则,而是指导方针。在实际开发中,应该根据具体情况灵活应用这些原则,以达到最佳的设计效果。