单例模式[Singleton Pattern]类图
[img]http://dl.iteye.com/upload/attachment/266520/46c5fc30-682e-33a7-95b6-21c76714a3d6.png[/img]
这里我们来看下这个单例模式注册器如何工作的:
光有代码是看不出如何调用的,我们需要看看如何调用这个注册器,例如:
这里将需要实现单例模式的类的构造方法使用protected来修饰,通过getInstance方法来获得这个单例的实例。
[url=http://dl.iteye.com/topics/download/8e892505-90d3-3e0f-9333-e11a78bf9c16]单例模式[Singleton Pattern] example code[/url]
[img]http://dl.iteye.com/upload/attachment/266520/46c5fc30-682e-33a7-95b6-21c76714a3d6.png[/img]
这里我们来看下这个单例模式注册器如何工作的:
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方法来获得这个单例的实例。
[url=http://dl.iteye.com/topics/download/8e892505-90d3-3e0f-9333-e11a78bf9c16]单例模式[Singleton Pattern] example code[/url]