我今天在采访中被问到什么是接口(interface)隔离原则以及与之相反的情况或原则是什么。
ISP对我来说很清楚,但我不知道问题的第二部分,与ISP相反的原理是什么?
最佳答案
来自维基百科:
The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.
与之相反的是客户端被迫依赖于它不使用的方法。这可能表现为实现一个它不需要的接口(interface),该接口(interface)的方法层太宽,或者一个类定义了几个客户端不需要的抽象方法。
一个例子(首先是接口(interface)):
public interface Book {
String getAuthor();
String getGenre();
String getPageCount();
String getWeight();
}
public interface EBook extends Book {
// Oh no - ebooks don't have weight, so that should always return zero!
// But it makes no sense to include it as an attribute of the interface.
}
抽象方法的例子:
public abstract class Shape {
public abstract double getVolume();
public abstract double getHeight();
public abstract double getLength();
public abstract double getWidth();
public abstract Color getColor();
}
public class Line extends Shape {
public double length;
public Color color;
// Kind of forced to have a volume...
public double getVolume() {
return 0;
}
/// ...and a height...
public double getHeight() {
return 0;
}
// ...and a width...
public double getWidth() {
return 0;
}
public double getLength() {
return length;
}
public Color getColor() {
return color;
}
}
关于java - 与接口(interface)隔离原则相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29132163/