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

相关推荐
小湘西16 小时前
拓扑排序(Topological Sort)
python·设计模式
蜜獾云19 小时前
设计模式之观察者模式:监听目标对象的状态改变
观察者模式·设计模式·rxjava
知无不研20 小时前
中介者模式
c++·设计模式·中介者模式
bmseven20 小时前
大白话讲解23种设计模式简介
设计模式
蜜獾云20 小时前
设计模式之代理模式:本地接口代理远程接口的调用
设计模式·系统安全·代理模式
蜜獾云20 小时前
设计模式之访问者模式:动态的给目标对象增加新功能
设计模式·访问者模式
蜜獾云1 天前
设计模式之策略模式:替换掉糟糕的if else语句实现面向对象编程而非面向过程
设计模式·策略模式
蜜獾云1 天前
设计模式之状态模式:封装数据的状态流转逻辑
设计模式·状态模式
Serene_Dream1 天前
深度解析设计模式:单例模式(Singleton Pattern)
单例模式·设计模式
朱一头zcy1 天前
设计模式入门:最简单的单例模式
笔记·单例模式·设计模式