我有以下代码。如您所见,我正在执行类似的逻辑,但一次用于自行车,一次用于汽车。我可以使用 <K>
吗?减少重复代码?我没用过<K>
所以我不确定我可以将它合并到哪里以及如何合并。我在哪里可以决定是否调用getCarsWithFeature
或 getBikesWithFeature
?
最好的做法是减少行数(可能会降低可读性)还是使用这种看起来重复的代码?
public Set<Car> getPremiumCars(String filter) {
final Callable<Set<Car>> retryGetCars = new RetryingCallable<>(retryStrategy(), getCars(filter));
return retryGetCars.call();
}
public Callable<Set<Car>> getCars(String feature) {
return new Callable<Set<Car>>() {
@Override
public Set<Car> call() throws Exception {
Set<Car> cars = getCarsWithFeature(feature);
return Collections.unmodifiableSet(cars);
}
};
}
public Set<Bike> getPremiumBikes(String filter) {
final Callable<Set<Bike>> retryGetBikes = new RetryingCallable<>(retryStrategy(), getBikes(filter));
return retryGetBikes.call();
}
public Callable<Set<Bike>> getBikes(String feature) {
return new Callable<Set<Bike>>() {
@Override
public Set<Bike> call() throws Exception {
Set<Bike> bikes = getBikesWithFeature(feature);
return Collections.unmodifiableSet(bikes);
}
};
}
最佳答案
我不知道你的整个代码,但我建议这两个类都实现相同的接口(interface) - 让我们说 Vehicle
:
public interface Vehicle {
}
然后您可以编写最近可以重用的代码:
public <T extends Vehicle> Set<T> getPremiumVehicle(Function<String, Callable<Set<T>>> vehicleSupplier, String filter) throws Exception {
final Callable<Set<T>> retryGetCars = new RetryingCallable<T>(retryStrategy(), vehicleSupplier.apply(filter));
return retryGetCars.call();
}
public <T extends Vehicle> Callable<Set<T>> getVehicle(Function<String, Set<T>> vehicleSupplier, String feature) {
return () -> {
Set<T> vehicles = vehicleSupplier.apply(feature);
return Collections.unmodifiableSet(vehicles);
};
}
现在,您可以重用上面的代码,例如:
public Set<Car> getPremiumCars(String filter) throws Exception {
return getPremiumVehicle(this::getCars, filter);
}
public Set<Bike> getPremiumBikes(String filter) throws Exception {
return getPremiumVehicle(this::getBikes, filter);
}
public Callable<Set<Car>> getCars(String feature) {
return getVehicle(this::getCarsWithFeature, feature);
}
public Callable<Set<Bike>> getBikes(String feature) {
return getVehicle(this::getBikesWithFeature, feature);
}
关于java - 使用泛型 <K> 减少重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48878723/