0105_接口隔离原则
定义:客户端不应该被迫依赖它们不使用的接口
场景
这里还以人类对象为例,人类属性有年龄、名称,动作有吃饭、行走。运动员的动作有跑步、跳远。
反例
IHuman接口
- 职责:人类行为接口,定义了人类的基本行为规范
public interface IHuman {
/**
* 吃饭行为
*/
void eat();
/**
* 走路行为
*/
void walk();
/**
* 跑步行为 - 运动员
*/
void run();
/**
* 跳跃行为 - 运动员
*/
void jump();
}
Human类
- 职责:实现了IHuman接口定义的基础人类行为
public class Human implements IHuman {
private int age;
private String name;
public Human(int age, String name) {
this.age = age;
this.name = name;
}
public void eat() {
System.out.println(this.name + "在吃饭");
}
public void walk() {
System.out.println(this.name + "在走路");
}
public void run() {
System.out.println(this.name + "在跑步");
}
public void jump() {
System.out.println(this.name + "在跳跃");
}
}
在反例中,Human类违返了接口隔离原则,实现了运动员才具有的动作,需要将其拆分为多个专门的接口。
正例

LifeBehavior接口
- 职责:基础生命行为接口
public interface LifeBehavior {
/**
* 进食行为
* 所有生物都需要通过进食来获取能量
*/
void eat();
/**
* 行走行为
* 生物通过行走来移动位置
*/
void walk();
}
SportBehavior接口
- 职责:运动行为接口
public interface SportBehavior {
/**
* 跑步行为
*/
void run();
/**
* 跳跃行为
*/
void jump();
}
BaseHuman类
- 职责:只处理人类基本属性和基本生存行为
public class BaseHuman implements LifeBehavior{
private int age;
private String name;
public BaseHuman(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public void eat() {
System.out.println(this.name + "在吃饭");
}
@Override
public void walk() {
System.out.println(this.name + "在走路");
}
public String getName() {
return name;
}
}
AthleteHuman类
- 职责:继承了人类基本属性和基本生存行为,并处理运动员特有的行为
public class AthleteHuman extends BaseHuman implements SportBehavior {
public AthleteHuman(int age, String name) {
super(age, name);
}
/**
* 跑步方法
*/
public void run() {
System.out.println(getName() + "在跑步");
}
/**
* 跳远方法
*/
public void jump() {
System.out.println(getName() + "在跳远");
}
}
总结
通过将臃肿的接口拆分为更小、更具体的接口,可以避免实现类承担不必要的职责,提高系统的灵活性和可维护性。

浙公网安备 33010602011771号