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

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.

主站蜘蛛池模板: 合川市| 巫山县| 峡江县| 阿拉善左旗| 揭阳市| 和静县| 岑巩县| 栖霞市| 双城市| 大足县| 永康市| 无为县| 玉溪市| 来安县| 五常市| 微博| 吴川市| 安阳市| 德昌县| 大同县| 德州市| 淳化县| 靖边县| 石嘴山市| 汪清县| 亚东县| 顺昌县| 威信县| 都兰县| 三门峡市| 石门县| 平阴县| 藁城市| 东山县| 昆明市| 吉安县| 齐齐哈尔市| 平安县| 秦安县| 武川县| 望谟县|