- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 112字
- 2021-06-25 20:52:33
Simple factory with class registration using reflection
For this method, we are going to use a map to keep the product IDs along with their corresponding classes:
private Map<String, Class> registeredProducts = new HashMap<String,Class>();
Then, we add a method to register new vehicles:
public void registerVehicle(String vehicleId, Class vehicleClass)
{
registeredProducts.put(vehicleId, vehicleClass);
}
The create method becomes the following:
public Vehicle createVehicle(String type) throws InstantiationException, IllegalAccessException
{
Class productClass = registeredProducts.get(type);
return (Vehicle)productClass.newInstance();
}
In certain situations, working with reflection is either impossible or discouraged. Reflection requires a runtime permission that may not be present in certain environments. If performance is an issue, reflection may slow the program and so should be avoided.