您的位置 首页 知识分享

SOLID 原则 – 使用 Python 中的真实示例进行解释

坚实的原则(图片来源:freecodecamp) solid 是一个缩写词,代表五项设计原则,可帮助开发人员创…

SOLID 原则 - 使用 Python 中的真实示例进行解释

坚实的原则(图片来源:freecodecamp)

solid 是一个缩写词,代表五项设计原则,可帮助开发人员创建更易于维护、更易于理解和更灵活的软件。让我们用一个相关的例子来逐一介绍。

1. s – 单一责任原则 (srp)

定义:一个类应该只有一个改变的理由,这意味着它应该只有一项工作或职责。

说明:假设您有一个工具结合了两种不同的任务,例如发送电子邮件和处理付款。如果这两个任务都由一个类处理,则电子邮件功能的更改可能会破坏付款功能。通过将这些职责分开,您可以最大限度地减少某一部分的变化影响另一部分的风险。

示例

class emailsender:     def send_email(self, recipient, subject, body):         # code to send an email         print(f"sending email to {recipient} with subject '{subject}'")  class paymentprocessor:     def process_payment(self, amount):         # code to process payment         print(f"processing payment of amount {amount}")  # usage email_sender = emailsender() email_sender.send_email("user@example.com", "hello!", "welcome to our service!")  payment_processor = paymentprocessor() payment_processor.process_payment(100) 
登录后复制

在此示例中,emailsender 仅负责发送电子邮件,而 paymentprocessor 仅负责处理付款。他们每个人都有一个职责,使代码更容易维护和扩展。

立即学习“”;

点击下载“”;

2. o – 开闭原理 (ocp)

定义:软件实体(如类、模块、函数等)应该对扩展开放,但对修改关闭。

解释:这意味着您应该能够向类添加新功能或行为,而无需更改其现有代码。假设您有一个支付处理系统,并且您想要添加一种新的支付方式。您应该能够在不修改现有代码的情况下添加这个新方法。

示例

from abc import abc, abstractmethod  class paymentprocessor(abc):     @abstractmethod     def process_payment(self, amount):         pass  class creditcardpayment(paymentprocessor):     def process_payment(self, amount):         print(f"processing credit card payment of {amount}")  class paypalpayment(paymentprocessor):     def process_payment(self, amount):         print(f"processing paypal payment of {amount}")  # usage payments = [creditcardpayment(), paypalpayment()] for payment in payments:     payment.process_payment(100) 
登录后复制

在此示例中,paymentprocessor 是一个抽象类,它定义了用于处理付款的合约。 creditcardpayment 和 paypalpayment 是扩展此类的实现。如果您想添加新的付款方式,您可以创建一个扩展 paymentprocessor 的新类,而无需修改现有类。

3. l – 里氏替换原理 ()

定义:子类型必须可以替换其基本类型,而不改变程序的正确性。

解释:这意味着超类的对象应该可以用子类的对象替换,而不影响程序的功能。例如,如果您有一个适用于 vehicle 类的函数,那么它也应该适用于任何子类,例如 car 或 bike。

示例

class vehicle:     def start_engine(self):         pass  class car(vehicle):     def start_engine(self):         print("starting car engine...")  class bike(vehicle):     def start_engine(self):         print("starting bike engine...")  # usage def start_vehicle_engine(vehicle: vehicle):     vehicle.start_engine()  car = car() bike = bike()  start_vehicle_engine(car)  # should work fine start_vehicle_engine(bike) # should work fine 
登录后复制

在此示例中,car 和 bike 是 vehicle 的子类。 start_vehicle_engine 函数可以与 vehicle 的任何子类一起工作,而不需要知道子类的具体情况,这符合里氏替换原则。

4. i – 接口隔离原则 (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 multifunctiondevice(printer, scanner):     def print(self, document):         print(f"printing: {document}")      def scan(self, document):         print(f"scanning: {document}")  # usage mfd = multifunctiondevice() mfd.print("document 1") mfd.scan("document 2") 
登录后复制

这里,打印机和扫描仪是独立的接口。 multifunctiondevice 实现了两者,但如果存在仅打印或仅扫描的设备,则它们不需要实现不使用的方法,遵循接口隔离原则。

5. d – 依赖倒置原则(dip)

定义:高层模块不应该依赖于低层模块。两者都应该依赖于抽象(例如接口)。抽象不应该依赖于细节。细节应该取决于抽象。

说明:高级类不应直接依赖于低级类,而应依赖于接口或抽象类。这允许更大的灵活性和更容易的维护。

示例

from abc import ABC, abstractmethod  class NotificationService(ABC):     @abstractmethod     def send(self, message):         pass  class EmailNotificationService(NotificationService):     def send(self, message):         print(f"Sending email: {message}")  class SMSNotificationService(NotificationService):     def send(self, message):         print(f"Sending SMS: {message}")  class NotificationSender:     def __init__(self, service: NotificationService):         self.service = service      def notify(self, message):         self.service.send(message)  # Usage email_service = EmailNotificationService() sms_service = SMSNotificationService()  notifier = NotificationSender(email_service) notifier.notify("Hello via Email")  notifier = NotificationSender(sms_service) notifier.notify("Hello via SMS") 
登录后复制

在此示例中,notificationsender 依赖于notificationservice 抽象,而不是依赖于像emailnotificationservice 或smsnotificationservice 这样的具体类。这样,您就可以在不更改notificationsender类的情况下切换通知服务。

结论

  • 单一职责原则(srp):一个类应该做一件事,并且把它做好。

  • 开闭原则(ocp):类应该对扩展开放,但对修改关闭。

  • 里氏替换原则(lsp):子类应该可以替换它们的基类。

  • 接口隔离原则 (isp):任何客户端都不应被迫依赖于它不使用的方法。

  • 依赖倒置原则(dip):依赖于抽象,而不是具体实现。

通过遵循这些 solid 原则,您可以创建更易于理解、维护和扩展的软件。

以上就是SOLID 原则 – 使用 Python 中的真实示例进行解释的详细内容,更多请关注php中文网其它相关文章!

本文来自网络,不代表甲倪知识立场,转载请注明出处:http://www.spjiani.cn/wp/1319.html

作者: nijia

发表评论

您的电子邮箱地址不会被公开。

联系我们

联系我们

0898-88881688

在线咨询: QQ交谈

邮箱: email@wangzhan.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部