当我的操作没有得到所有实施者的支持时,设计界面的正确方法是什么?

Was*_*RAR 8 java methods implementation interface class

我有一个接口和两个正在实现接口的类.

public interface MyInterface {
    public void firstMethod();  
    public int secondMethod();
}

public class MyClass1 implements MyInterface  {
    public void firstMethod() {}
}

public class MyClass2 implements MyInterface  {
    public void firstMethod() {}
    public int secondMethod() {}
}
Run Code Online (Sandbox Code Playgroud)

这堂课MyClass1告诉我Add unimplemented methods,因为secondMethod没有实施,好的我会这样做.但问题是我不需要这种方法MyClass1.

在您看来,最好的做法是什么?

  1. 使用类似的方法添加未实现的方法 return 0
  2. 如果我不想实现它,还有另一种方法可以解决这个问题.

Joh*_*lla 15

您应该执行以下操作之一:

  1. 将界面分解为更小的部分并根据需要进行组合.这是首选方法,尤其是在您控制的情况下MyInterface.

  2. 返回最合理的默认值.

  3. 扔一个UnsupportedOperationException.


这是一个更具说明性的例子.假设您的界面如下所示:

public interface Driveable {
  public Position accelerate(Vector v, Time t);
  public String getVehicleIdentificationNumber();
}
Run Code Online (Sandbox Code Playgroud)

如果您MyClass1实际上是一个Boat并且没有车辆识别号码,那么您实施此功能是没有意义的.事实上,这实际上是错误的.其他客户希望您拥有此值,但您无法将其提供给他们.

如果需要,最好使用正确的切片将接口块组合成较小的块.例如,您可能会写这样:

public interface Driveable {
  public Position accelerate(Vector v, Time t);
}

public interface Vehicle extends Driveable {
  public String getVehicleIdentificationNumber();
}

public class Boat implements Driveable { ... }
public class Car implements Vehicle { ... }
Run Code Online (Sandbox Code Playgroud)

这是最好的方法,因为它根据需要在接口上完全分割责任.

如果真的你的域重要的是所有Driveables有一个车辆识别号码,而这仅仅是其中的车辆识别号码未知或不可用的特殊情况,那么你可以提供一个默认的实现:

public String getVehicleIdentificationNumber() {
  return "";
}
Run Code Online (Sandbox Code Playgroud)

如果您的域中根本没有返回车辆识别号码,那么您应该抛出异常:

public String getVehicleIdentificationNumber() {
  throw new UnsupportedOperationException("vehicle identification
    number not supported on boats");
}
Run Code Online (Sandbox Code Playgroud)