java - 如何利用Spring Boot原生支持更好的实现工厂模式?

标签 java spring-boot factory-pattern

在 Spring boot 中实现工厂模式的最佳方式。

我有一个接口(interface)和它的多个实现。在请求期间,我需要根据输入字符串返回 bean。

我可以通过多种方式做到这一点。但是最好的方式是什么?

interface vehicle {
void drive();
string getVehicleName();
}

@Component
public class Car implements vehicle {
  private static string prop = "car";
  @Override
  string getVehicleName() { return prop;}

  @Override
  void drive() {}
}

@Component
public class Bike implements vehicle {
  private static string prop = "bike";

  @Override
  string getVehicleName() { return prop;}

  @Override
  void drive() {}
}

@Service
public class VehicleFactory {
    @Autowired
    private List<vehicle> vehicles;

    private static final HashMap<String, vehicle> requestVehicleMap = new HashMap<>();

    @PostConstruct
    public void initVehicleFactory() {
        for(vehicle vehicle : vehicles) {
            requestVehicleMap.put(vehicle.getVehicleName(), request);
        }
    }

    public static vehicle getVehicleImpl(String vehicleName) {
        return requestVehicleMap.get(vehicleName);
    }
}

这确实给了我正确的类(class)。 还有“限定符”可以用作 Implementing custom factory pattern in Spring .

但是有更好的方法吗?

最佳答案

接口(interface)和它的实现都很好,我只想单独更改工厂类,因为我已经得到了实现列表,那么为什么还要在映射中初始化它

我也会在代码中评论建议

车辆工厂

@Service
public class VehicleFactory {

    @Autowired
    private List<Vehicle> vehicles;

    public Vehicle getVehicleImpl(String vehicleName) { // You have already declared as @Service then why use static
          return vehicles.stream()
                .filter(vehicle -> vehicle.getVehicleName().equalsIgnoreCase(vehicleName)) // This will filter the Impl you needed from others
                .findFirst() 
                .orElseThrow(() -> new RuntimeException(String.format(" Invlaid Vehicle Name - %s", vehicleName))); // Incase Impl is not found it should throw an error or handle in some other ways
    }
}

所以尝试一下

关于java - 如何利用Spring Boot原生支持更好的实现工厂模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56492522/

相关文章:

java - cron.xml - 验证错误

java - springSecurityFilterChain - ObjectPostProcessor 是必需的 bean 异常

java - Spring Boot 2 无法将属性读取为字符串

java - Fragment : Setting the class variables vs putting the Bundle as arguments in the Fragment 的工厂方法

Java 1.4 工厂问题

java - GRPC:用Java/Scala制作高吞吐量客户端

Java静态枚举方法返回默认枚举值

java - Spring框架有命令行界面吗

c++ - 试图引用对象工厂中已删除的函数

java - Java 中枚举列表的结尾