接口隔离原则
Interface Segregation Principle
1. 客户端不应该依赖它不需要的接口
即一个类对另一个类的依赖应该建立在最小的接囗上
2.UML图
3. 最小接口实现
类A通过接囗Interface1依赖类B,
类c通过接囗Interface1依赖类D,
如果接囗Interface1对于类A和类C来说不是最小接囗,那么类B和类D必须去实现他们不要的方法。
4. 按接口隔离原则应当这样处理
将接囗Interface1拆分为独立的几个接囗,类A和类C分别与他们需要的接口建立依赖关系。也就是采用接口隔离原则
5. demo
案例1(图1)
• B,D实现接口,
• A通过Interface1会依赖B的1、2、3方法
• C依赖D的1、4、5方法
• 接口不隔离的时候,B、D需要实现接口的所有方法,而实际使用的方法并不是全部
案例2可实现接口隔离(图2)
• 接口拆分成三个,接口1为公共的,接口2,3为需要单独隔离开的
• B实现接口1、2,D实现接口1、3,
• A通过Interface1,Interface2依赖B的1、2、3方法
• C通过Interface1,Interface3依赖D的1、4、5方法
接口隔离的时候,B、D分别实现对应需要的接口所有方法,实现接口隔离
public class Segregation2{
public static void main(String args[]){
A a = new A();
a.depent1(new B());//A通过接口Interface1依赖Boperation1()
a.depent2(new B());
a.depent3(new B());
C c = new C();
c.depent1(new D());
c.depent2(new D());
c.depent3(new D());
}
}
/**
* 接口定义
*/
interface Interface1{
void operation1();
}
interface Interface2{
void operation2();
void operation3();
}
interface Interface3{
void operation4();
void operation5();
}
/**
* 接口隔离实现
*/
class B implements Interface1,Interface2{
public void operation1(){
System.out.println("B implements operation1");
}
public void operation2(){
System.out.println("B implements operation2");
}
public void operation3(){
System.out.println("B implements operation3");
}
}
class D implements Interface1,Interface3{
public void operation1(){
System.out.println("D implements operation1");
}
public void operation4(){
System.out.println("D implements operation4");
}
public void operation5(){
System.out.println("D implements operation5");
}
}
class A{
public void depent1(Interface1 interface1){
interface1.operation1();
}
public void depent2(Interface2 interface2){
interface2.operation2();
}
public void depent3(Interface2 interface2){
interface2.operation3();
}
}
class C{
public void depent1(Interface1 interface1){
interface1.operation1();
}
public void depent2(Interface3 interface3){
interface3.operation4();
}
public void depent3(Interface3 interface3){
interface3.operation5();
}
}
6. 运行结果
B implements operation1
B implements operation2
B implements operation3
D implements operation1
D implements operation4
D implements operation5