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