认识设计模式SOLID原则

在这里插入图片描述

SOLID 是一个缩写词,代表面向对象编程 (OOP) 的五个设计原则,旨在促进更简单、更健壮和可更新的代码。 SOLID 缩写中的每个字母都代表了开发易于维护和随时间扩展的软件的原则。

SOLID原则是面向对象编程和设计的五项基本指导原则,由罗伯特·C·马丁(Robert C. Martin)提出,用于帮助开发者构建更加健壮、可维护和可扩展的软件系统。SOLID是这五个原则首字母的缩写,分别代表:

单一职责原则(SRP):一个类只应承担一种责任。

开闭原则(OCP):软件实体(类、模块、函数等)应该对扩展开放,对修改封闭。

里氏替换原则(LSP):所有派生类都应该能够替换其基类。

依赖倒置原则(DIP):高层模块不应该依赖低层模块;两者都应该依赖抽象。

接口隔离原则(ISP):不应该强迫客户依赖他们不使用的接口。

简写 全称 中文描述
SRP The Single Responsibility Principle 单一功能原则
OCP The Open Closed Principle 开放封闭原则(开闭原则)
LSP The Liskov Substitution Principle 里氏替换原则
DIP The Dependency Inversion Principle 依赖倒置原则
ISP The Interface Segregation Principle 接口分离原则
  1. 单一职责原则(Single Responsibility Principle, SRP)
  • 这个原则指出一个类或者模块应当只负责一项职责,即仅有一个引起它变化的原因。这样可以减少类之间的耦合,使得类更易于理解、测试和维护。

  • Example: Instead of a User class that handles both user data and password validation, separate the concerns into UserData and PasswordValidator classes.

  1. 开闭原则(Open/Closed Principle, OCP)
  • 开放封闭原则要求软件实体(类、模块、函数等)应该对扩展开放,对修改关闭。也就是说,可以在不修改原有代码的基础上通过扩展来增加新的功能,从而支持软件的持续演进。
  • Example: Use inheritance or interfaces to add new functionality without modifying existing code. For instance, create a PaymentGateway interface and implement specific payment gateways like Stripe or PayPal without changing the underlying code.
  1. 里氏替换原则(Liskov Substitution Principle, LSP)
  • 里氏替换原则强调在面向对象设计中,子类应当能够替换其父类并且不会影响到程序的正确性。换言之,使用父类的地方能够透明地使用子类的对象,而不会引发错误或异常行为。

  • Example: A Square class that inherits from a Rectangle class should be able to be used as a Rectangle without affecting the correctness of the program.

  1. 依赖倒置原则(Dependency Inversion Principle, DIP)
  • 依赖倒置原则主张高层模块不应依赖于低层模块,二者都应该依赖于抽象。同时,抽象不应该依赖于细节,细节应当依赖于抽象。这通常通过依赖注入等方式实现,有助于降低耦合,提高灵活性。

  • Example: Instead of a Vehicle interface with multiple methods (e.g., drive(), fly(), sail()), create separate interfaces for each type of vehicle (e.g., Drivable, Flyable, Sailable).

  1. 接口隔离原则(Interface Segregation Principle, ISP)
  • 接口隔离原则提倡客户端不应被迫依赖它不需要的接口。应当将大型接口拆分为更小、更具体的接口,这样客户端只会看到它关心的方法,降低了耦合度。

  • Example: Use dependency injection to provide a Database abstraction to a UserService class, allowing you to switch from a MySQL database to a PostgreSQL database without changing the UserService code.

SOLID原则的应用

SOLID原则可以应用于各个层面的软件设计,从类设计到系统架构。遵循SOLID原则可以帮助开发人员设计出更易于维护、更灵活的软件。

Python
# 单一职责原则
class EmailSender:
    def send_email(self, recipient, subject, body):
        # 发送邮件的代码

class SMSNotifier:
    def send_sms(self, phone_number, message):
        # 发送短信的代码

# 开闭原则
class Shape:
    def draw(self):
        pass

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

    def draw(self):
        # 绘制矩形的代码

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def draw(self):
        # 绘制圆形的代码

# 里氏替换原则
class Animal:
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        print("汪汪汪")

class Cat(Animal):
    def make_sound(self):
        print("喵喵喵")

# 接口隔离原则
class IPaymentProcessor:
    def process_payment(self, amount):
        pass

class CreditCardProcessor(IPaymentProcessor):
    def process_payment(self, amount):
        # 处理信用卡支付的代码

class PayPalProcessor(IPaymentProcessor):
    def process_payment(self, amount):
        # 处理PayPal支付的代码

# 依赖倒置原则
class OrderService:
    def __init__(self, payment_processor):
        self.payment_processor = payment_processor

    def place_order

遵循SOLID原则有助于提升代码的质量,使得软件更容易理解和维护,同时也为未来的修改和扩展打下了良好的基础。然而,在实际应用中,开发者需要根据项目的实际情况灵活运用这些原则,有时候过分追求遵循每一个原则可能会带来不必要的复杂度。

参考

相关推荐

  1. 设计模式SOLID设计原则

    2024-05-09 05:22:03       33 阅读
  2. 设计模式】02-SOLID 设计原则

    2024-05-09 05:22:03       56 阅读
  3. 设计类的时候面向对象遵循的原则 SOLID

    2024-05-09 05:22:03       59 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-09 05:22:03       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-09 05:22:03       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-09 05:22:03       87 阅读
  4. Python语言-面向对象

    2024-05-09 05:22:03       96 阅读

热门阅读

  1. CNN模型

    CNN模型

    2024-05-09 05:22:03      38 阅读
  2. 代码随想录算法训练营第四十六天

    2024-05-09 05:22:03       37 阅读
  3. matlab中interp2函数应用

    2024-05-09 05:22:03       33 阅读
  4. WinDbg 常用的SOS命令

    2024-05-09 05:22:03       39 阅读
  5. QTDay3

    QTDay3

    2024-05-09 05:22:03      31 阅读
  6. LeetCode 每日一题 2024/4/29-2024/5/5

    2024-05-09 05:22:03       34 阅读
  7. 嘉楠堪智 CanMV K230 进行 C 语言程序开发

    2024-05-09 05:22:03       33 阅读
  8. 树莓派的几种登录方式、及登录失败解决方式

    2024-05-09 05:22:03       34 阅读
  9. C++笔试训练

    2024-05-09 05:22:03       28 阅读
  10. 18.Docker学习

    2024-05-09 05:22:03       29 阅读