设计模式 之 “单例模式[Singleton Pattern]”
单例模式[Singleton Pattern]类图
这里我们来看下这个单例模式注册器如何工作的:
package m.utils; import java.util.HashMap; import org.apache.log4j.Logger; /** * 单例模式注册器 * */ public class SingletonRegistry { public static SingletonRegistry REGISTRY = new SingletonRegistry(); private static HashMap map = new HashMap(); private static Logger logger = Logger.getRootLogger(); protected SingletonRegistry() { // Exists to defeat instantiation } public static synchronized Object getInstance(String classname) { Object singleton = map.get(classname); if(singleton != null) { return singleton; } try { singleton = Class.forName(classname).newInstance(); logger.info("created singleton: " + singleton); } catch(ClassNotFoundException cnf) { logger.fatal("Couldn't find class " + classname); } catch(InstantiationException ie) { logger.fatal("Couldn't instantiate an object of type " + classname); } catch(IllegalAccessException ia) { logger.fatal("Couldn't access class " + classname); } map.put(classname, singleton); return singleton; } }光有代码是看不出如何调用的,我们需要看看如何调用这个注册器,例如:
public class Singleton { protected Singleton() { // Exists only to thwart instantiation. } public static Singleton getInstance() { return (Singleton)SingletonRegistry.REGISTRY.getInstance("m.pattern.Singleton"); } }这里将需要实现单例模式的类的构造方法使用protected来修饰,通过getInstance方法来获得这个单例的实例。
单例模式[Singleton Pattern] example code