本文共 893 字,大约阅读时间需要 2 分钟。
import java.util.concurrent.ConcurrentHashMap;public class Factory { private ConcurrentHashMapregistedList = new ConcurrentHashMap (); 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; }}
转载地址:http://sthii.baihongyu.com/