我对使用接口的最佳实践提出了这个问题。请看这段代码:
这些是接口:
public interface Vehicle {
public int getAcceleration();
}
public interface Flying extends Vehicle {
public int getAltitude();
public void up(int seconds);
public void down(int seconds);
}
public interface Runner extends Vehicle {
public int getSpeed();
public void accelerate(int seconds);
public void decelerate(int seconds);
}
这将是Runner接口的实现:
public class RunnerImplementation implements Runner {
Vehicle vehicle;
int speed;
public RunnerImplementation(Vehicle v) {
vehicle = v;
}
@Override
public int getAcceleration() {
return vehicle.getAcceleration();
}
@Override
public int getSpeed() {
return speed;
}
@Override
public void accelerate(int seconds) {
speed += seconds * getAcceleration();
}
@Override
public void decelerate(int seconds) {
speed -= seconds * getAcceleration();
}
}
这将是Flying的接口实现:
public class FlyingImplementation implements Flying {
Vehicle vehicle;
int altitude;
public FlyingImplementation(Vehicle v) {
vehicle = v;
}
@Override
public int getAcceleration() {
return vehicle.getAcceleration();
}
@Override
public int getAltitude() {
return altitude;
}
@Override
public void up(int seconds) {
altitude += seconds * getAcceleration();
}
@Override
public void down(int seconds) {
altitude -= seconds * getAcceleration();
}
}
这就是结果,FlyingCar类:
public class FlyingCar extends BaseVehicle implements Flying, Runner {
Flying flying = null;
Runner runner = null;
public FlyingCar() {
flying = new FlyingImplementation(this);
runner = new RunnerImplementation(this);
}
@Override
public int getSpeed() {
return runner.getSpeed();
}
@Override
public void accelerate(int seconds) {
runner.accelerate(seconds);
}
@Override
public void decelerate(int seconds) {
runner.decelerate(seconds);
}
@Override
public int getAltitude() {
return flying.getAltitude();
}
@Override
public void up(int seconds) {
flying.up(seconds);
}
@Override
public void down(int seconds) {
flying.down(seconds);
}
}
如你所见:
RunnerImplementation
和FlyingImplementation
的每个接口。 Vehicle
对象作为参数传递给构造函数。Runner
和Flying
定义为来自Vehicle
的扩展名,因为我想证明它们在语义上是相关的,但这迫使我实施两次方法getAcceleration()
。一种方法很容易,但如果Vehicle
有100种方法,我就有问题......我首先想到的是Runner
和Flying
都不应该从Vehicle
扩展,但我将失去语义关系。我的问题:
RunnerImplementation
和FlyingImplementation
在FlyingCar
课程中使用接口是一种很好的做法吗? TIA,
答案 0 :(得分:1)
我只需要FLyingCar
实现Flying
和Runner
,因为它还会实现Vehicle
(两个接口都扩展它)。我没有看到实现接口只是为了将实现用作其他类的基类(除非你将拥有大量不同的对象类型)。