- 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.
推薦閱讀
- Python機器學習:數據分析與評分卡建模(微課版)
- C語言程序設計基礎與實驗指導
- Practical DevOps
- 計算機應用基礎案例教程
- LabVIEW虛擬儀器程序設計從入門到精通(第二版)
- Flowable流程引擎實戰
- Python數據可視化之美:專業圖表繪制指南(全彩)
- Python Social Media Analytics
- Python數據預處理技術與實踐
- Elasticsearch搜索引擎構建入門與實戰
- Processing開發實戰
- Java EE互聯網輕量級框架整合開發:SSM+Redis+Spring微服務(上下冊)
- 3ds Max瘋狂設計學院
- Hands-On GUI Application Development in Go
- C++ Primer(中文版)(第5版)