package com.tan.principle.interface_segregation;
public class InterfaceSegregationDemo1 {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.depend1(b);
D d = new D();
C c = new C();
c.depend1(d);
}
}
interface Interface1 {
void method1();
void method2();
void method3();
void method4();
void method5();
}
class B implements Interface1 {
public void method1() {
System.out.println("B实现了method1");
}
public void method2() {
System.out.println("B实现了method2");
}
public void method3() {
System.out.println("B实现了method3");
}
public void method4() {
System.out.println("B实现了method4");
}
public void method5() {
System.out.println("B实现了method5");
}
}
class D implements Interface1 {
public void method1() {
System.out.println("D实现了method1");
}
public void method2() {
System.out.println("D实现了method2");
}
public void method3() {
System.out.println("D实现了method3");
}
public void method4() {
System.out.println("D实现了method4");
}
public void method5() {
System.out.println("D实现了method5");
}
}
//A类通过接口Interface1依赖(使用)B类,但是只会用到1,2,3方法
class A{
public void depend1(Interface1 i){
i.method1();
}
public void depend2(Interface1 i){
i.method2();
}
public void depend3(Interface1 i){
i.method3();
}
}
//C类通过接口Interface1依赖(使用)D类,但是只会用到1,4,5方法
class C{
public void depend1(Interface1 i){
i.method1();
}
public void depend4(Interface1 i){
i.method4();
}
public void depend5(Interface1 i){
i.method5();
}
}
package com.tan.principle.interface_segregation.improve;
public class InterfaceSegregationDemo2 {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.depend1(b);
D d = new D();
C c = new C();
c.depend1(d);
}
}
//接口1
interface Interface1 {
void method1();
}
//接口2
interface Interface2 {
void method2();
void method3();
}
//接口3
interface Interface3 {
void method4();
void method5();
}
class B implements Interface1,Interface2 {
public void method1() {
System.out.println("B实现了method1");
}
public void method2() {
System.out.println("B实现了method2");
}
public void method3() {
System.out.println("B实现了method3");
}
}
class D implements Interface1,Interface3 {
public void method1() {
System.out.println("D实现了method1");
}
public void method4() {
System.out.println("D实现了method4");
}
public void method5() {
System.out.println("D实现了method5");
}
}
//A类通过接口Interface1,接口Interface2依赖(使用)B类
class A{
public void depend1(Interface1 i){
i.method1();
}
public void depend2(Interface2 i){
i.method2();
}
public void depend3(Interface2 i){
i.method3();
}
}
//C类通过接口Interface1,接口Interface3依赖(使用)D类
class C{
public void depend1(Interface1 i){
i.method1();
}
public void depend4(Interface3 i){
i.method4();
}
public void depend5(Interface3 i){
i.method5();
}
}