接口隔离原则
676字约2分钟
设计模式
2022-04-28
Clients should not be forced to depend upon interfaces that they do not use
客户端不应该被强迫依赖它不需要的接口
问题由来: 类A通过接口I依赖类B, 类C通过接口I依赖类D, 如果接口I对于类A和类B来说不是最小接口, 则类B和类D必须去实现他们不需要的方法.
解决方案: 将臃肿的接口I拆分为独立的几个接口, 类A和类C分别与他们需要的接口建立依赖关系. 也就是采用接口隔离原则.
接口
- 一组 API 接口集合
- 单个 API 接口或函数
- OOP 中的接口概念
一组 API 接口集合
如果把"接口"理解为一组接口集合, 可以是某个微服务的接口, 也可以是某个类库的接口等. 如果部分接口只被部分调用者使用, 我们就需要将这部分接口隔离出来, 单独给这部分调用者使用, 而不强迫其他调用者也依赖这部分不会被用到的接口.
单个 API 接口或函数
函数的设计要功能单一, 不要将多个不同的功能逻辑在一个函数中实现(判定功能是否单一, 除了很强的主观性, 还需要结合具体的场景)
如果把"接口"理解为单个 API 接口或函数, 部分调用者只需要函数中的部分功能, 那我们就需要把函数拆分成粒度更细的多个函数, 让调用者只依赖它需要的那个细粒度函数.
OOP 中的接口概念
如果把"接口"理解为 OOP 中的接口, 也可以理解为面向对象编程语言中的接口语法. 那接口的设计要尽量单一, 不要让接口的实现类和调用者, 依赖不需要的接口函数.
接口隔离原则与单一职责原则的区别
单一职责原则针对的是模块、类、接口的设计. 接口隔离原则相对于单一职责原则, 一方面更侧重于接口的设计, 另一方面它的思考角度也是不同的. 接口隔离原则提供了一种判断接口的职责是否单一的标准: 通过调用者如何使用接口来间接地判定. 如果调用者只使用部分接口或接口的部分功能, 那接口的设计就不够职责单一.
merge部分