文章目录
接口隔离原则问题描述解决思路代码实现传统方法接口隔离
接口隔离原则
Interface Segregation Principle
客户端不应该依赖它不需要的接口
,即一个类对另一个类的依赖应该建立在最小的接口上
问题描述
类A通过接口Interface1依赖类B
,类C通过interface1依赖类D
,如果接口Interface1对于类A和类C都不是最小接口
,
那么类B和类D必须去实现他们不需要的方法
解决思路
按隔离原则应该这样处理
:
将接口interface1拆分成为独立的几个接口
,类A和类C分别与他们需要的接口建立依赖关系
,也就是采用接口隔离原则
代码实现
传统方法
public class Segregation {
public static void main(String
[] args
) {
new A().method(new B());
new C().method(new D());
}
}
class A{
public void method(Interface1 i
){
i
.opreation1();
i
.operation2();
i
.operation3();
}
}
class C{
public void method(Interface1 i
){
i
.opreation1();
i
.operation4();
i
.operation5();
}
}
class B implements Interface1{
public void opreation1() {
System
.out
.println("B 实现了operation1");
}
public void operation2() {
System
.out
.println("B 实现了operation2");
}
public void operation3() {
System
.out
.println("B 实现了operation3");
}
public void operation4() {
System
.out
.println("B 实现了operation4");
}
public void operation5() {
System
.out
.println("B 实现了operation5");
}
}
class D implements Interface1{
public void opreation1() {
System
.out
.println("D 实现了operation1");
}
public void operation2() {
System
.out
.println("D 实现了operation2");
}
public void operation3() {
System
.out
.println("D 实现了operation3");
}
public void operation4() {
System
.out
.println("D 实现了operation4");
}
public void operation5() {
System
.out
.println("D 实现了operation5");
}
}
interface Interface1{
void opreation1();
void operation2();
void operation3();
void operation4();
void operation5();
}
接口隔离
public class Segregation {
public static void main(String
[] args
) {
new A().method(new B());
new C().method(new D());
}
}
class A {
public void method(Interface2 i
) {
i
.opreation1();
i
.operation2();
i
.operation3();
}
}
class C {
public void method(Interface3 i
) {
i
.opreation1();
i
.operation4();
i
.operation5();
}
}
class B implements Interface1 ,Interface2
{
public void opreation1() {
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 opreation1() {
System
.out
.println("D 实现了operation1");
}
public void operation4() {
System
.out
.println("D 实现了operation4");
}
public void operation5() {
System
.out
.println("D 实现了operation5");
}
}
interface Interface1 {
void opreation1();
}
interface Interface2 extends Interface1{
void operation2();
void operation3();
}
interface Interface3 extends Interface1{
void operation4();
void operation5();
}