單例模式(3.註冊式)
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.";
}
}