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

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.

主站蜘蛛池模板: 哈巴河县| 石林| 青岛市| 连城县| 花莲县| 大同县| 离岛区| 保靖县| 嘉禾县| 东明县| 延寿县| 团风县| 崇礼县| 阜康市| 新竹市| 独山县| 五常市| 长兴县| 西乌| 阿瓦提县| 筠连县| 乐平市| 永和县| 吴江市| 扎赉特旗| 宁晋县| 苍山县| 屯昌县| 平谷区| 宁南县| 启东市| 华容县| 阿坝| 卫辉市| 靖江市| 淮安市| 平陆县| 长宁区| 叙永县| 秦皇岛市| 平江县|