
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
3.4 接口隔离原则
3.4.1 接口隔离原则的定义
接口隔离原则(Interface Segregation Principle,ISP)指用多个专门的接口,而不使用单一的总接口,客户端不应该依赖它不需要的接口。这个原则指导我们在设计接口时,应当注意以下几点。
(1)一个类对另一个类的依赖应该建立在最小接口上。
(2)建立单一接口,不要建立庞大臃肿的接口。
(3)尽量细化接口,接口中的方法尽量少(不是越少越好,一定要适度)。
接口隔离原则符合“高聚合、低耦合”的设计思想,使得类具有很好的可读性、可扩展性和可维护性。在设计接口的时候,要多花时间思考,要考虑业务模型,包括还要对以后可能发生变更的地方做一些预判。所以,在实际开发中,我们对抽象、业务模型的理解是非常重要的。
3.4.2 使用接口隔离原则解决实际问题
我们来写一个动物行为的抽象。
IAnimal接口的代码如下。


Bird类实现的代码如下。

Dog类实现的代码如下。

由上面代码可以看出,Bird类的swim()方法可能只能空着,Dog类的fly()方法显然是不可能的。这时候,我们针对不同动物的行为来设计不同的接口,分别设计IEatAnimal、IFlyAnimal和ISwimAnimal接口。
IEatAnimal接口的代码如下。

IFlyAnimal接口的代码如下。

ISwimAnimal接口的代码如下。

Dog只实现IEatAnimal和ISwimAnimal接口。


我们来看两种类图的对比,如下图所示,还是非常清晰明了的。
