package test;
import java.util.HashMap;
public class RegSingleton {
private static HashMap m_registry = new HashMap();
static {
RegSingleton x = new RegSingleton();
m_registry.put(x.getClass().getName(), x);
}
// 注意该构造器不能是私有的,子类构造器需要调用
public RegSingleton() {
}
public static RegSingleton getInstance(String name) {
if (name == null) {
name = "test.RegSingleton";
}
if (m_registry.get(name) == null) {
try {
m_registry.put(name, Class.forName(name).newInstance());
} catch (Exception e) {
System.out.println("Error happened.");
}
}
return (RegSingleton) (m_registry.get(name));
}
}
package test;
public class RegSingletonChild extends RegSingleton {
/**
* 构造器不能为private,父类getInstance方法需要调用该构造器
*/
public RegSingletonChild() {
}
/**
* 静态工厂方法
*/
public static RegSingletonChild getInstance() {
return (RegSingletonChild) RegSingleton.getInstance("test.RegSingletonChild");
}
public String toString() {
return "I am RegSingletonChild's instance.";
}
}