设计模式:接口隔离原则(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 小时前
深入理解 AbortController:从底层原理到跨语言设计哲学
javascript·设计模式·node.js
likerhood15 小时前
抽象工厂设计模式(Abstract Factory Pattern)
设计模式
张涛酱10745615 小时前
AskUserQuestionTool 深入解析:构建人机协作的交互桥梁
spring·设计模式·ai编程
Duang16 小时前
AI 真能自己写出整个 Windows 系统吗?我做了一场无监督实验
算法·设计模式·架构
t***54417 小时前
能否给出更多现代C++设计模式的示例
开发语言·c++·设计模式
t***54417 小时前
这些设计模式在现代C++中如何应用
java·c++·设计模式
我爱cope20 小时前
【从0开始学设计模式-8| 桥接模式】
java·设计模式·桥接模式
AI大法师1 天前
从 Firefox Kit 看懂品牌升级的正确顺序
大数据·人工智能·设计模式·firefox
天若有情6731 天前
原创C++设计模式:功能归一化——无继承、轻量版AOP,比传统OOP更优雅
开发语言·c++·设计模式·oop
绿豆人2 天前
Go设计模式学习
学习·设计模式·golang