1

今天在一次采访中被问到什么是接口隔离原则,与此相反的情况或原则是什么。

ISP对我来说很清楚,但我不知道问题的第二部分,与ISP相反的原理是什么?

4

1 回答 1

3

来自维基百科:

接口隔离原则 (ISP) 指出不应强迫任何客户端依赖它不使用的方法。

与之相反的是客户端被迫依赖于它不使用的方法。这可能表现为实现一个不需要的接口,该接口在一个层的方法过于宽泛,或者一个类定义了多个客户端不需要的抽象方法。

一个例子(首先是接口):

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;
    }
}
于 2015-03-18T20:47:29.397 回答