Introduction
Switch case statements are commonly used in programming to perform different actions
based on the value of a particular variable or condition.
While switch case statements can be effective for simple scenarios,
They often become unwieldy and hard to maintain as the number of cases and complexity of logic increases.
This is where the Factory Design Pattern comes into play,
Especially when you use the switch case with always the same condition in different methods or endpoints
I will give for you an example where you could convert the switch cases using polymorphism and Factory Pattern.
The Use case :
In this example we have different Operations for different vehicles, each vehicle will execute the operation
differently.
how do we know that vehicle A or vehicle B will do the staff ?
based on a Type that we receive as parameter.
OperationService :
public Details runOperation(String type, Input input) {
var vehicleService = factory.getVehicleService(type);
return vehicleService.run(input);
}
So that was the method in the Global service where we call the factory,
And this is the VehicleService :
public interface VehicleService {
Details run(Input input);
}
You can create either interface or a class or abstract these are some services that
could implement that interface:
@Service
public class CarService implements VehicleService {
@Override
public Details run(Input input) {
system.out.println("Car running");
}
}
suppose we have another Service that represents a Vehicle :
@Service
public class TrainService implements VehicleService {
@Override
public Details run(Input input) {
system.out.println("Train running");
}
}
Now that we have our Structure, this is the Resolver / Factory,
It depends on context, here i have used Spring boot which created already the services for me.
if i didn’t do so, i would have created the Services in the Factory.
So for this reason, i chose to name the class a VehicleServiceResolver :
@Component
@RequiredArgsConstructor
public class VehicleServiceResolver {
private final TrainService trainService;
private final CarService carService;
public VehicleService getVehicleService(String type) {
return switch (type.toLowerCase()) {
case "car" -> carService;
case "train" -> trainService;
default -> throw new IllegalArgumentException("The type provided is not found");
};
}
}
Explanation
In this resolver, we encapsulate the Switch having the condition on the type of the Vehicle,
we choose which service will execute the task ( the task here is the run).
This is a minimalist example with Only One method run,
Imagine having several methods like that and having to do the switch case on every Operation method
The Factory/ Resolver here saved as a lot by encapsulating the choice of the vehicle in the Resolver.
Ajouter un commentaire
Commentaires