设计模式原则
—— 接口统一原则
1. 基本介绍
客户端(即:使用类)不应该依赖它不需要的接口,即一个类对另一个类的依赖应该建立在最小接口上
2. 实例应用
1. 当依赖的接口中方法过多情况
1. 实例目标:
类A
通过接口Interface1
使用类B
的operation1
,operation2
,operation3
方法;
类C
通过接口Interface1
使用类D
的operation1
,operation4
,operation5
方法;
2. 类图:
3. 代码:
// Interface1 接口
public interface Interface1 {
void operation1();
void operation2();
void operation3();
void operation4();
void operation5();
}
// 类B
public class B implements Interface1{
public void operation1() {
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");
}
}
// 类D
public class D implements Interface1{
public void operation1() {
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");
}
}
// 类A
public class A {
public void depend1(Interface1 i){
i.operation1();
}
public void depend2(Interface1 i){
i.operation2();
}
public void depend3(Interface1 i){
i.operation3();
}
}
// 类C
public class C {
public void depend1(Interface1 i){
i.operation1();
}
public void depend4(Interface1 i){
i.operation4();
}
public void depend5(Interface1 i){
i.operation5();
}
}
// 测试类
public class Test {
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
a.depend1(b);
a.depend2(b);
a.depend3(b);
c.depend1(d);
c.depend4(d);
c.depend5(d);
}
}
4. 运行结果:
5. 分析问题:
未完待续。。。
如果本文有错误或对本文有不理解的地方欢迎评论 ^_^
如果本文有帮助到您,可以点一下右上角的赞哦,谢谢啦