设计模式:接口隔离原则(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

相关推荐
绿豆人14 小时前
Go设计模式学习
学习·设计模式·golang
逮到647了16 小时前
23种设计模式简述
设计模式
爱吃烤鸡翅的酸菜鱼18 小时前
【Java】封装位运算通用工具类——用一个整数字段替代几十个布尔列,极致节省存储空间
java·开发语言·设计模式·工具类·位运算·合成复用原则
geovindu18 小时前
go: Model,Interface,DAL ,Factory,BLL using mysql
开发语言·mysql·设计模式·golang·软件构建
guojb82419 小时前
当 Vue 3 遇上桥接模式:手把手教你优雅剥离虚拟滚动的业务大泥球
vue.js·设计模式
我登哥MVP20 小时前
【Spring6笔记】 - 15 - Spring中的八大设计模式
java·spring boot·笔记·spring·设计模式·intellij-idea
无籽西瓜a20 小时前
【西瓜带你学设计模式 | 第十六期 - 迭代器模式】迭代器模式 —— 统一遍历实现、优缺点与适用场景
java·后端·设计模式·迭代器模式·软件工程
程序员小寒21 小时前
JavaScript设计模式(十):模板方法模式实现与应用
前端·javascript·设计模式·模板方法模式
likerhood21 小时前
关于三种工厂的设计模式总结
设计模式
榴莲omega21 小时前
第14天:React 工程化与设计模式
前端·react.js·设计模式