模式回顧---單例
最近突然想回顧一下設計模式,很多東西是要回過頭來總結一下的。今天先回顧一下單例吧。很多時候覺得挺搞笑的,去面試的時候如果人家問你設計模式,一般都是要你寫個單例模式。去年來北京好幾家面試都是問我這個。當時我就想這個能反映出一個人的水平來嗎?還是說更多的是反映出這個公司的水平呢?
隨著一年的應用,很多地方都用過之后覺得,單例這個東西雖然簡單,可是現實是復雜的。所以單例這個簡單的模式也不能太小瞧咯。
單例其實有很多種實現,這是其中的一種,延遲加載的(好像英文叫Lazy?):
[下面代碼中所有的構造器都是私有的,這里我就省略不寫了。]
public static ClassName getInstance(){
if(instance == null)
{
instance = new ClassName();
}
return instance;
}
private static ClassName instance;
}
(一)
public static ClassName getInstance(){
return instance;
}
private static ClassName instance = new ClassName();
}
(二)
public static synchronized ClassName getInstance(){
if(instance == null)
{
instance = new ClassName();
}
return instance;
}
private static ClassName instance;
}
public static ClassName getInstance(){
if(instance == null)
{
instance = ClassName.createInstance();
}
return instance;
}
private static synchronized ClassName createInstance(){
if(instance == null)
{
return new ClassName();
}else{
return instance;
}
}
private static ClassName instance;
}
還有一種寫法是這樣的,這個不是延遲加載的。而是采用了一種取巧的方式。
public static ClassName getInstance(){
if(!instance.isInit)
{
instance.initSingleton();
}
return instance;
}
private synchronized void initSingleton() {
if(!isInit)
{
reset();//這名字是有點怪異,我沒時間想太好聽的名字
isInit = true;
}
}
public void reset(){
//.....真正進行數據初始化的地方
}
private boolean isInit = false;
private static ClassName instance = new ClassName();
}
將所有的初始化代碼搬到構造器之外。這是專為數據初始化和復位進行的設計。所以我把reset開放了出來。
posted on 2008-01-29 21:59 咖啡屋的鼠標 閱讀(1451) 評論(7) 編輯 收藏 所屬分類: Java