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

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.

主站蜘蛛池模板: 福清市| 灵川县| 友谊县| 莆田市| 太康县| 锦州市| 会同县| 玉龙| 阿巴嘎旗| 晴隆县| 枣强县| 五家渠市| 泊头市| 扎鲁特旗| 张北县| 武山县| 石景山区| 洪雅县| 漳州市| 静乐县| 阿拉善右旗| 保德县| 赫章县| 文登市| 龙井市| 定西市| 秭归县| 冀州市| 顺昌县| 札达县| 象山县| 安西县| 民和| 韩城市| 小金县| 孝义市| 中山市| 阿拉善右旗| 钦州市| 馆陶县| 莒南县|