设计模式七大原则之接口隔离原则
什么是接口隔离原则
一个类对另一个类的依赖应该建立在最小的接口上。
举个栗子
interface Animal {
void run();
void fly();
void swim();
void eat();
void sleep();
}
class Bird implements Animal {
@Override
public void run() { }
@Override
public void fly() { System.out.println("Bird fly..."); }
@Override
public void swim() { }
@Override
public void eat() { System.out.println("Bird eat..."); }
@Override
public void sleep() { System.out.println("Bird sleep..."); }
}
class Fish implements Animal {
@Override
public void run() { }
@Override
public void fly() { }
@Override
public void swim() { System.out.println("Fish swim..."); }
@Override
public void eat() { System.out.println("Fish eat..."); }
@Override
public void sleep() { System.out.println("Fish sleep..."); }
}
class Human implements Animal {
@Override
public void run() { System.out.println("Human run..."); }
@Override
public void fly() { System.out.println("Human fly airplanes..."); }
@Override
public void swim() { System.out.println("Human swim..."); }
@Override
public void eat() { System.out.println("Human eat..."); }
@Override
public void sleep() { System.out.println("Human sleep..."); }
}
Bird类除了基础的eat和sleep方法外,仅需要一个fly方法,但Animal接口中却规定了两个Bird所不需要的方法,Fish类同理(一般的鸟不会跑和游泳,一般的鱼也不会飞和跑),不遵循接口隔离原则。
此时需要对Animal接口进行拆分:
interface BaseAnimal {
void eat();
void sleep();
}
interface Flyable {
void fly();
}
interface Swimable {
void swim();
}
interface Runable {
void run();
}
class Bird implements BaseAnimal, Flyable {
@Override
public void fly() { System.out.println("Bird fly..."); }
@Override
public void eat() { System.out.println("Bird eat..."); }
@Override
public void sleep() { System.out.println("Bird sleep..."); }
}
class Fish implements BaseAnimal, Swimable {
@Override
public void swim() { System.out.println("Fish swim..."); }
@Override
public void eat() { System.out.println("Fish eat..."); }
@Override
public void sleep() { System.out.println("Fish sleep..."); }
}
class Human implements BaseAnimal, Flyable, Swimable, Runable {
@Override
public void run() { System.out.println("Human run..."); }
@Override
public void fly() { System.out.println("Human fly airplanes..."); }
@Override
public void swim() { System.out.println("Human swim..."); }
@Override
public void eat() { System.out.println("Human eat..."); }
@Override
public void sleep() { System.out.println("Human sleep..."); }
}
现在来看,Bird类仅需要实现Flyable接口和BaseAnimal接口中的方法而无需实现游泳和跑的方法,Fish类仅需要实现Swimable接口和BaseAnimal接口中的方法而无需实现飞和跑的方法,Human由于可以使用工具上天入地,因此需要实现Flyable、Swimable、Runable和BaseAnimal四个接口。
既保证了功能,又去除了不需要的方法实现。