java - 使用泛型 <K> 减少重复代码?

标签 java oop generics inheritance

我有以下代码。如您所见,我正在执行类似的逻辑,但一次用于自行车,一次用于汽车。我可以使用 <K> 吗?减少重复代码?我没用过<K>所以我不确定我可以将它合并到哪里以及如何合并。我在哪里可以决定是否调用getCarsWithFeaturegetBikesWithFeature

最好的做法是减少行数(可能会降低可读性)还是使用这种看起来重复的代码?

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/

相关文章:

java - 剪刀石头布蜥蜴史波克不返回任何东西

c# - 如何使用 Unity.WebApi 通过接口(interface)实例访问类属性

delphi - 如何制作这个OO?

java - 结合深度泛型集合

java - 获取所有扩展类并推断某些泛型的类

java - 如何调用同名不同返回值的不同类型对象的方法?

java - 以编程方式外部化 logback-spring.xml

java - JSON VS 简单的字符串操作来解析 Android 中的 HttpRequest

java - 在计算数据库中的元素时出现致命异常?

ios - 为什么默认调用父类(super class)指定的初始值设定项?