【代码积累】replace constructor with factory

来源:互联网 发布:mac百度云下载速度慢 编辑:程序博客网 时间:2024/06/06 14:04
import java.util.concurrent.ConcurrentHashMap;public class Factory {private ConcurrentHashMap<String, Object> registedList = new ConcurrentHashMap<String, Object>();public void register(String name,Object object) {registedList.put(name, object);}private static Factory factory = null;public Vehicle createSpecifiedVehicle(String name) {return ((Vehicle)registedList.get(name)).createObject();/*This is not gonna work as when createSpecifiedVehicle is called the static blocks in sub-classes has not been  * executed yet so registedList is actually empty.Static block in a class will be executed at the time the class * is being load,and only when the class is needed it will be loaded by ClassLoader.*/}public static Factory getInstance() {if( null == factory ) {synchronized(Factory.class) {if( null == factory ) {factory = new Factory();}}}return factory;}}