【代码积累】replace constructor with factory

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;
	}
}

你可能感兴趣的:(【代码积累】replace constructor with factory)