單例模式

單例模式確保某一個類只有一個實例,而且自行實例化並向整個系統提供這個實例。

一、單例模式的特點

  • 單例類只能有一個實例
  • 單例類必須自己創建自己的唯一實例
  • 單例類必須給其他對象提供這一實例 

二、單例模式的具體實現

餓漢模式:
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;
	}
}
進行兩次是否爲空的判斷,第一次爲了減少不必要的同步,第二次當Singleton爲null時,才創建實例。這種寫法可以減少資源的消耗和多餘的同步,解決線程安全問題。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章