1. 經(jīng)典的單實例模式例子(非線程安全):
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
本例是最經(jīng)典的單實例模式例子,但是在多線程的情況下就會產(chǎn)生多個實例!
2. 線程安全的例子:
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
增加synchronized,會讓該方法是線程安全的,但是會引起每個線程在調(diào)用該方法時的等待,如果getInstance的性能對應(yīng)用程序不是很關(guān)鍵(記住,同步方法可能會使getInstance方法得運行效率降低100倍),本方法是最好得方法!
3. 提前實例化,不適用延遲實例化(使用于創(chuàng)建和運行時負擔(dān)不太繁重或者應(yīng)用程序總是創(chuàng)建并使用單件實例),它是線程安全得:
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
return uniqueInstance;
}
// other useful methods here
}
采用這種方法,我們依賴JVM在加載這個類時候馬上創(chuàng)建此唯一實例,JVM保證在任何線程訪問它之前,一定先創(chuàng)建它!
4. 在java1.5及以后的版本,增加了volatile關(guān)鍵字,可以采用雙重檢查加鎖!
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
volatile關(guān)鍵字確保:當(dāng)unigueInstance變量在被初始化成實例時,多個線程能夠正確的處理它!(對于關(guān)注性能的程序,這種做法可以大大減少時耗)