设计模式:接口隔离原则(Interface Segregation Principle,ISP)介绍

接口隔离原则(Interface Segregation Principle,ISP)是面向对象设计原则之一,它强调一个类不应该依赖于它不需要的接口。接口隔离原则的核心思想是将大的接口拆分成更小的、更具体的接口,客户端应该仅依赖于它们需要使用的接口

实现接口隔离原则的原理包括以下几点:

  1. 将大接口拆分成小接口: 将一个大的接口拆分成多个更小、更具体的接口,每个接口都应该包含客户端所需的方法。

  2. 接口要单一职责: 每个接口应该只包含一个单一的职责或者功能,这样可以避免客户端依赖于不需要的方法。

  3. 避免接口的臃肿: 接口应该精简、清晰,避免包含过多的方法,以确保每个接口的职责清晰明确。

在 Python 中,实现接口隔离原则可以通过以下方式:

python 复制代码
# 抽象类
'''
    大的接口拆分成多个更小、更具体的接口: printer, scanner
    每个接口应该只包含一个单一的职责或者功能, 避免接口的臃肿
'''
class Printer:
    def print_c1(self, content):
        pass

class Scanner:
    def scan_c1(self, content):
        pass

# 具体类
class PrintSimple(Printer):
    def print_c1(self, content):
        print('print:', content)

class User:
    def __init__(self, printsimple):
        self.printsimple = printsimple

    def print_document(self, document):
        self.printsimple.print_c1(document)


printsimple = PrintSimple()

user = User(printsimple)

user.print_document('document name')

运行结果:

print: document name

相关推荐
blueSatchel8 小时前
STM32F4系列使用ISP下载后,导致芯片被读写保护,无法烧录程序
stm32·嵌入式硬件·接口隔离原则
ZHE|张恒10 小时前
设计模式(十二)代理模式 — 用代理控制访问,实现延迟加载、权限控制等功能
设计模式·代理模式
SakuraOnTheWay10 小时前
《深入设计模式》学习(1)—— 深入理解OOP中的6种对象关系
设计模式
q***718511 小时前
Java进阶-SpringCloud设计模式-工厂模式的设计与详解
java·spring cloud·设计模式
白衣鸽子11 小时前
告别参数地狱:业务代码中自定义Context的最佳实践
后端·设计模式·代码规范
帅中的小灰灰1 天前
C++编程建造器设计模式
java·c++·设计模式
ZHE|张恒1 天前
设计模式(十)外观模式 — 提供统一入口,简化复杂系统的使用
设计模式·外观模式
howcode1 天前
女友去玩,竟带回一道 “虐哭程序员” 的难题
后端·设计模式·程序员
apigfly2 天前
深入Android系统(十三)Android的窗口系统
android·设计模式·源码
y***54882 天前
Java设计模式之观察者模式
观察者模式·设计模式