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

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.

主站蜘蛛池模板: 靖宇县| 张家界市| 孝昌县| 德令哈市| 通城县| 宜宾县| 阳山县| 芷江| 扎鲁特旗| 稻城县| 乐清市| 四子王旗| 通渭县| 盘山县| 酉阳| 纳雍县| 福州市| 马鞍山市| 儋州市| 上饶县| 梅河口市| 柯坪县| 扎囊县| 宜宾县| 阳山县| 休宁县| 盐津县| 上高县| 靖江市| 辽宁省| 临沧市| 武城县| 利津县| 闻喜县| 浪卡子县| 郯城县| 松溪县| 内丘县| 昂仁县| 涡阳县| 清苑县|