官术网_书友最值得收藏!

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();
}
主站蜘蛛池模板: 敦化市| 彭阳县| 运城市| 桂阳县| 锦州市| 天全县| 手游| 南城县| 司法| 景德镇市| 镇雄县| 安国市| 永泰县| 康马县| 深州市| 方城县| 夹江县| 博野县| 虞城县| 电白县| 平江县| 弥勒县| 从江县| 法库县| 朝阳市| 阿巴嘎旗| 岳阳市| 马鞍山市| 弋阳县| 敦化市| 正定县| 清徐县| 长阳| 莲花县| 砀山县| 鄂尔多斯市| 河东区| 香格里拉县| 阿勒泰市| 同心县| 汉川市|