设计模式 - 设计原则 - 接口隔离原则

  • 总结
    • 什么是面向接口编程?
    • 什么是依赖?如何表示在UML中?
    • 什么是接口隔离原则?

  • 了解的背景内容:
    • 我们通常使用面向接口编程,比如我们定义一个接口,然后其他类实现这个接口,那么在某个类使用的时候直接用作接口当作类型,而不具体指定类,当调用的时候可以传入实现了这个接口的类
    • 依赖的概念:表示一个对象使用另外一个对象的功能,比如一个对象调用另外一个对象中的方法,在UML中用以下图示表示
  • 什么是接口隔离
    • 一个类对另外一个类的依赖应该建立在最小接口上
      • 也就是说一个接口中的方法应该尽可能的少,如果太多会导致其实现类实现过多不需要的方法
      • 换一个角度说接口方法不应该过多,如果过多应该拆分,通过implement来实现多个接口
  • 具体的实现代码如下


public class Segregation1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 使用一把
		A a = new A();
		a.depend1(new B()); // A类通过接口去依赖B类
		a.depend2(new B());
		a.depend3(new B());

		C c = new C();

		c.depend1(new D()); // C类通过接口去依赖(使用)D类
		c.depend4(new D());
		c.depend5(new D());

	}

}

// 接口1
interface Interface1 {
	void operation1();

}

// 接口2
interface Interface2 {
	void operation2();

	void operation3();
}

// 接口3
interface Interface3 {
	void operation4();

	void operation5();
}

class B implements Interface1, Interface2 {
	public void operation1() {
		System.out.println("B 实现了 operation1");
	}

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

	public void operation3() {
		System.out.println("B 实现了 operation3");
	}

}

class D implements Interface1, Interface3 {
	public void operation1() {
		System.out.println("D 实现了 operation1");
	}

	public void operation4() {
		System.out.println("D 实现了 operation4");
	}

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

class A { // A 类通过接口Interface1,Interface2 依赖(使用) B类,但是只会用到1,2,3方法
	public void depend1(Interface1 i) {
		i.operation1();
	}

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

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

class C { // C 类通过接口Interface1,Interface3 依赖(使用) D类,但是只会用到1,4,5方法
	public void depend1(Interface1 i) {
		i.operation1();
	}

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

	public void depend5(Interface3 i) {
		i.operation5();
	}
}


Prev Post webpack5开发模式配置
Next Post 设计模式 - 设计原则 - 单一职责原则