簡體   English   中英

如何通過Spring Boot本機支持更好地實現工廠模式?

[英]How to implement factory pattern better with spring boot native support?

在Spring Boot中實現工廠模式的最佳方法。

我有一個接口及其多種實現。 在請求期間,我需要根據輸入字符串返回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);
    }
}

這確實給了我正確的課堂。 還有一個“限定符”可以在Spring中用作實現自定義工廠模式

但是有更好的方法嗎?

接口及其實現都很好,我只需要更改Factory類,因為您已經獲得了實現列表,然后又為什么要在Map中對其進行初始化

我還將評論代碼中的建議

車輛工廠

@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
    }
}

所以試試吧

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM