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

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();
}
主站蜘蛛池模板: 白玉县| 高唐县| 会宁县| 井研县| 晴隆县| 通河县| 深泽县| 江油市| 郓城县| 武隆县| 宁化县| 大石桥市| 太谷县| 刚察县| 双峰县| 宣城市| 凉城县| 独山县| 饶河县| 文昌市| 江永县| 常州市| 左贡县| 峡江县| 双柏县| 长岭县| 黄冈市| 精河县| 乌拉特前旗| 上饶县| 贺兰县| 江华| 怀宁县| 剑阁县| 宾阳县| 介休市| 江城| 永泰县| 肥东县| 永新县| 左云县|