- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 112字
- 2021-06-25 20:52:33
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.
推薦閱讀
- VMware View Security Essentials
- 玩轉Scratch少兒趣味編程
- JavaScript全程指南
- 算法精粹:經典計算機科學問題的Java實現
- C/C++算法從菜鳥到達人
- 基于Java技術的Web應用開發
- Visual Basic程序設計教程
- Java軟件開發基礎
- 小學生C++創意編程(視頻教學版)
- C語言課程設計
- 零基礎學單片機C語言程序設計
- Mastering Data Mining with Python:Find patterns hidden in your data
- Web Developer's Reference Guide
- Oracle Database XE 11gR2 Jump Start Guide
- 深入理解Java虛擬機:JVM高級特性與最佳實踐