我有一个接口(interface)和两个实现接口(interface)的类。
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() {}
}
MyClass1
类告诉我添加未实现的方法
,因为secondMethod
没有实现,好的,我会这样做。但问题是我在 MyClass1
中不需要这个方法。
您认为最好的做法是什么?
- 添加未实现的方法,如
return 0
- 如果我不想实现它,还有另一种方法可以解决这个问题。
最佳答案
您应该执行以下操作之一:
将界面分成更小的部分并根据需要进行组合。这是首选方法,尤其是当您控制
<MyInterface
时。尽可能返回最合理的默认值。
抛出一个
UnsupportedOperationException
。
这是一个更具说明性的例子。假设您的界面如下所示:
public interface Driveable {
public Position accelerate(Vector v, Time t);
public String getVehicleIdentificationNumber();
}
如果您的 MyClass1
实际上是一个 Boat
并且没有车辆识别号,那么您实现它就没有意义。事实上,它实际上是错误的。其他客户希望你有这个值(value),但你不能给他们。
最好将接口(interface)分块和组合成更小的部分,必要时使用正确的切片。例如,您可以这样写:
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 { ... }
这是最好的方法,因为它根据需要跨接口(interface)准确划分职责。
如果在您的域中确实重要的是所有 Driveable 都具有车辆识别号,并且这只是车辆识别号未知或不可用的特殊情况,那么您可以提供默认实现:
public String getVehicleIdentificationNumber() {
return "";
}
如果在您的域中返回车辆识别号是完全错误的,那么您应该抛出一个异常:
public String getVehicleIdentificationNumber() {
throw new UnsupportedOperationException("vehicle identification
number not supported on boats");
}
关于java - 当我有并非所有实现者都支持的操作时,设计界面的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6843557/