Reputation: 499
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?
Upvotes: 2
Views: 4283
Reputation: 1528
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
@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
Upvotes: 1