我的目标是理解接口隔离原理,同时实现多态。
我的预期结果:我可以通过接口隔离原则实现多态性。
我的实际结果:不,我不能。我被迫创建样板并使用 Liskov 替换原则(如果有 Worker,则必须有一个不能吃的 Worker,所以为 Worker 创建一个可以吃的接口,扩展 Worker)。我想我误解了接口隔离原则。
这是违反接口隔离原则的代码。
public interface IWorker {
void work();
void eat();
}
class Human implements IWorker {
public void work() {
System.out.println("Human is working.");
}
public void eat() {
System.out.println("Human is eating.");
}
}
class Robot implements IWorker {
public void work() {
System.out.println("Robot is working.");
}
public void eat() {
throw new UnsupportedOperationException("Robot cannot eat");
}
}
我被告知将接口分成2。
public interface IEatable {
void eat();
}
interface IWorkable {
void work();
}
class Human implements IWorkable, IEatable {
public void work() {
System.out.println("Human is working.");
}
public void eat() {
System.out.println("Human is eating.");
}
}
class Robot implements IWorkable {
public void work() {
System.out.println("Robot is working.");
}
}
解决方案是使用 Liskov 替换原则。
public interface IWorkable {
void work();
}
interface IEatable {
void eat();
}
interface IWorker extends IWorkable {
}
interface IHumanWorker extends IWorker, IEatable {
}