在Java中,要實現單例模式,可以使用懶漢式(Lazy Initialization)或餓漢式(Eager Initialization)。這里我將為您展示如何使用靜態變量實現懶漢式單例模式。
public class Singleton {
// 使用volatile關鍵字確保多線程環境下的正確性
private static volatile Singleton instance;
// 將構造方法設為私有,防止外部實例化
private Singleton() {
// 防止通過反射創建多個實例
if (instance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
// 提供一個靜態方法獲取唯一的實例
public static Singleton getInstance() {
// 雙重檢查鎖定(Double-Checked Locking)
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
在這個實現中,我們使用了volatile
關鍵字確保多線程環境下的正確性。getInstance()
方法首先檢查實例是否為空,如果為空,則進入同步塊。在同步塊中,再次檢查實例是否為空,如果仍然為空,則創建一個新的實例。這樣可以確保在多線程環境下,只有一個實例被創建。