最近
首先選用的是單實例模式
個人感覺懶漢型單例模式沒什麼
一個實例工廠
惡漢
Java代碼
public class EagerSingleton { private static final EagerSingleton m_instance = new EagerSingleton(); private EagerSingleton() { } public static EagerSingleton getInstance() { return m_instance; } }
懶漢
Java代碼
public class LazySingleton {
private static LazySingleton m_instance = null;
private LazySingleton() {
}
synchronized public static LazySingleton getInstance() {
if (m_instance == null) {
m_instance = new LazySingleton();
}
return m_instance;
}
}
注冊型
Java代碼
public class RegSingleton {
static private HashMap m_registry = new HashMap();
static {
RegSingleton x = new RegSingleton();
m_registry
}
protected RegSingleton() {
}
static public RegSingleton getInstance(String name) {
if (name == null) {
name =
}
if (m_registry
try {
m_registry
} catch (Exception e) {
System
}
}
return (RegSingleton) (m_registry
}
}
Java代碼
public class RegSingletonChild extends RegSingleton {
private RegSingletonChild() {
}
/**
* 靜態工廠方法
*/
static public RegSingletonChild getInstance() {
return (RegSingletonChild) RegSingleton
}
}
由於在我們這個系統中各種配置信息較多
Java代碼
public class ConfigClass {
static private HashMap m_registry = new HashMap();
static {
ConfigClass x = new ConfigClass();
m_registry
}
/**
* 保護的默認構造子
*/
protected ConfigClass() {
}
/**
* 靜態工廠方法
*/
static public ConfigClass getInstance(String name) {
if (name == null) {
name =
}
if (m_registry
try {
m_registry
} catch (Exception e) {
System
}
}
return (ConfigClass) (m_registry
}
}
Java代碼
public class ConfigImpl extends ConfigClass {
private List properties = null;
/**
* @return the properties
*/
public List getProperties() {
return properties;
}
private ConfigImpl() {
initalProperties();
}
public static ConfigImpl getInstance() {
return (ConfigImpl) ConfigClass
}
/**
*
* @author xiaofeng
* <B>Time</B> :
*/
public void updateProperties() {
ConfigImpl con = new ConfigImpl();
properties = con
}
/**
* @author xiaofeng
* <B>Time</B> :
*/
private void initalProperties() {
// 初始化配置信息
}
}
呵呵終於完成了
單實例顧名思義在一個JVM中只有一個實例
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27345.html