接口隔离原则 (Interface Segregation Principle)

基本介绍

  • 客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小的接口上。
  • 先看一张图:
  • 类 A 通过接口 Interface 依赖类 B,类 C 通过接口 Interface1 依赖类 D,如果接口 Interface1 对于类 A 和类 C来说不是最小接口,那么类 B 和类 D 必须去实现他们不需要的方法。
  • 按隔离原则应当这样处理:

    • 将接口 Interface1 拆分为独立的几个接口,类 A 和类 C 分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则。
package com.atguigu.principle.segregation;

/**
 * @author harrytsz
 * @create 2020-04-27 下午2:21
 */
public class Segregation2 {
    public static void main(String[] args) {
        A a = new A();
        a.depend1(new B());   // A 类通过接口依赖 B 类
        a.depend2(new B());   // A 类通过接口依赖 B 类
        a.depend4(new B());   // A 类通过接口依赖 B 类

        System.out.println("-----------------");
        
        C c = new C();
        c.depend1(new D());
        c.depend3(new D());
        c.depend5(new D());

    }
}

/**************************************************************************************/

/**
 * 接口 1: Interfaces1
 */
interface Interfaces1 {
    void operation1();
}

/**
 * 接口 2 : Interfaces2
 */
interface Interfaces2 {
    void operation2();
    void operation4();
}

/**
 * 接口 3 : Interfaces3
 */
interface Interfaces3 {
    void operation3();
    void operation5();
}

/**************************************************************************************/

/**
 *  类 B : 实现接口1和接口2
 */
class B implements Interfaces1, Interfaces2 {

    @Override
    public void operation1() {
        System.out.println("B 实现了 Operation1");
    }

    @Override
    public void operation2() {
        System.out.println("B 实现了 Operation2");
    }

    @Override
    public void operation4() {
        System.out.println("B 实现了 Operation4");
    }
}

/**
 * 类 D : 实现接口1和接口3
 */
class D implements Interfaces1, Interfaces3 {

    @Override
    public void operation1() {
        System.out.println("D 实现了 Operation1");
    }

    @Override
    public void operation3() {
        System.out.println("D 实现了 Operation3");
    }

    @Override
    public void operation5() {
        System.out.println("D 实现了 Operation5");
    }
}

/**
 * 类 A 
 */
class A {
    public void depend1(Interfaces1 i){
        i.operation1();
    }

    public void depend2(Interfaces2 i){
        i.operation2();
    }

    public void depend4(Interfaces2 i){
        i.operation4();
    }
}

/**
 * 类 C
 */

class C {
    public void depend1(Interfaces1 i){
        i.operation1();
    }

    public void depend3(Interfaces3 i){
        i.operation3();
    }

    public void depend5(Interfaces3 i){
        i.operation5();
    }
}
Last modification:April 27, 2020
如果觉得我的文章对你有用,请随意赞赏