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

相关推荐
ximu_polaris4 小时前
设计模式(C++)-行为型模式-备忘录模式
c++·设计模式·备忘录模式
05候补工程师5 小时前
[实战复盘] 拒绝 AI 屎山!我从设计模式中学到的“调教”AI 新范式
人工智能·python·设计模式·ai·ai编程
sg_knight10 小时前
Python 设计模式:迭代器模式——用优雅的方式遍历一切
python·设计模式·迭代器模式
ximu_polaris15 小时前
设计模式(C++)-行为型模式-解释器模式
c++·设计模式·解释器模式
钝挫力PROGRAMER15 小时前
static final 指向可变集合的设计模式
java·设计模式
霍格沃兹测试学院-小舟畅学18 小时前
我花一周拆解了企业级Skills库的全套设计模式
人工智能·设计模式
kyriewen1119 小时前
你的前端滤镜慢得像PPT?用Rust+WebAssembly,一秒处理4K图
开发语言·前端·javascript·设计模式·rust·ecmascript·powerpoint
混迹中的咸鱼19 小时前
C++ 23种设计模式
设计模式·c++23
咖啡八杯19 小时前
GoF设计模式——工厂方法模式
java·后端·设计模式
ximu_polaris1 天前
设计模式(C++)-行为型模式-中介者模式
c++·设计模式·中介者模式