设计模式七大原则之接口隔离原则 (Interface Segregation Principle)

接口隔离原则 (ISP: Interface Segregation Principle)有两种定义:客户端不应该依赖它不需要的接口;类间的依赖关系应该建立在最小的接口上。

类之间通过接口依赖的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 /**
* @author sunys
*/
public class Interfacesegregation {
public static void main(String[] args) {
B b = new B();
b.dependA(new A());
}
interface InterfaceCommon{
void methodA();
void methodOther();
}


private static class A implements InterfaceCommon{
public void methodA() {
System.out.println("A类方法");
}

public void methodOther() {
System.out.println("其他类方法");
}
}

private static class B {
public void dependA(InterfaceCommon interfaceCommon){
System.out.println("通过公共接口依赖A类调用A类方法");
}
}
}

在上面的例子中可以看出,我们使用B类时想通过公共接口InterfaceCommon依赖A类,调用A类实现的方法,但是A类在实现自己的方法时还必须去实现其他类的方法。因此,InterfaceCommon对于B来说不是最小的接口,违背了接口隔离原则。更改方案,将InterfaceCommon拆分为独立的接口,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @author sunys
*/
public class Interfacesegregation1 {
public static void main(String[] args) {
B b = new B();
b.dependC(new A());
}
private interface InterfaceA{
void methodA();
}

private interface InterfaceOther{
void methodOther();
}

private static class A implements InterfaceA{
public void methodA() {
System.out.println("A类方法");
}
}

private static class B {
public void dependC(InterfaceA interfaceA){
System.out.println("通过最小接口依赖A类调用A类方法");
}
}
}

采用接口隔离原则对接口进行约束时,要注意以下几点:

  • 接口尽量小,但是要有限度。对接口进行细化可以提高程序设计灵活性,但是如果过小,则会造成接口数量过多,使设计复杂化。所以一定要适度。
  • 为依赖接口的类定制服务,只暴露给调用的类它需要的方法,它不需要的方法则隐藏起来。只有专注地为一个模块提供定制服务,才能建立最小的依赖关系。
  • 提高内聚,减少对外交互。使接口用最少的方法去完成最多的事情。

接口隔离原则和单一职责的异同:

  • 共同点:
    这两种原则都是为了提高类的内聚性、降低它们之间的耦合性,体现了封装的思想。

  • 不同点:

  1. 侧重点不一样,单一职责原则注重的是类的功能职责单一;接口隔离原则注重的是对接口依赖的隔离;
  2. 约束对象不一样,单一职责原则主要约束类,它针对的是类的功能职责,程序的实现和细节;接口隔离原则主要约束接口,它针对的是接口模板功能的设计构建。

附:本次演示的项目地址
https://github.com/syshlang/java-design-principle