- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 184字
- 2021-06-25 20:52:33
Simple factory with class registration using Product.newInstance
In the previous code, we used reflection to instantiate new vehicles. If we have to avoid reflection, we can use a similar factory where to register the new vehicle classes the factory should be able to create. Instead of adding classes to the map, we are going to add instances of each type of object we want to register. Each product will be able to create a new instance of itself.
We start by adding an abstract method in the base Vehicle class:
abstract public Vehicle newInstance();
For each product, the method declared abstract in the base class must be implemented:
@Override
public Car newInstance()
{
return new Car();
}
In the factory class, we are going to change the map to keep the IDs of the objects along with the vehicle objects:
private Map<String, Vehicle> registeredProducts = new HashMap<String,Vehicle>();
Then we register a new type of vehicle by passing an instance of it:
public void registerVehicle(String vehicleId, Vehicle vehicle)
{
registeredProducts.put(vehicleId, vehicle);
}
We change the createVehicle method accordingly:
public AbstractProduct createVehicle(String vehicleId)
{
return registeredProducts.get(vehicleId).newInstance();
}
- 深度實(shí)踐OpenStack:基于Python的OpenStack組件開發(fā)
- Objective-C Memory Management Essentials
- TypeScript Blueprints
- Mastering QGIS
- Mastering Kotlin
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)之性能測(cè)試篇
- Visual Basic程序設(shè)計(jì)習(xí)題解答與上機(jī)指導(dǎo)
- Oracle Exadata專家手冊(cè)
- Flutter跨平臺(tái)開發(fā)入門與實(shí)戰(zhàn)
- UI設(shè)計(jì)全書(全彩)
- Python語(yǔ)言科研繪圖與學(xué)術(shù)圖表繪制從入門到精通
- TypeScript 2.x By Example
- WordPress Search Engine Optimization(Second Edition)
- Mastering XenApp?
- Microsoft XNA 4.0 Game Development Cookbook