單例模式確保某一個類只有一個實例,而且自行實例化並向整個系統提供這個實例。
一、單例模式的特點
- 單例類只能有一個實例
- 單例類必須自己創建自己的唯一實例
- 單例類必須給其他對象提供這一實例
二、單例模式的具體實現
public class EagerSingleton {
private static EagerSingleton EAGER_SINGLETON = new EagerSingleton();
// 私有化
private EagerSingleton() {
}
private static EagerSingleton getInstance() {
return EAGER_SINGLETON;
}
}
可以看出,在單例類被加載時,靜態變量EAGER_SINGLETON就會實例化,加載速度快,但是獲取對象的速度慢。而且這種基於類加載的機制避免了多線程同步的問題。public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
懶漢模式提供了一個靜態變量,第一次調用getInstance方法時,單例類會進行初始化,在多線程下不能正常工作。
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
這種模式相對於一般的懶漢模式可以在多線程中正常工作,但是每次調用都需要進行同步,這樣可能在多次調用時增加不必要的開銷。
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}