简体   繁体   中英

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

Best way to implement factory pattern in Spring boot.

I've an interface and multiple implementations of it. During a request, I need to return the bean based on an input string.

There are multiple ways I can do it.. But whats the best way?

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);
    }
}

This does give me correct class. Also there is "qualifier" that can be used as Implementing custom factory pattern in Spring .

But is there better approach?

Interface and it's Implementation are good, I would just change the Factory class alone because you already I got the List of Implementation then Why again to initialise it in a Map

I will also comment the suggestions in the code

VehicleFactory

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

So give it a try

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM