一、定義:單件模式--確保一個類只有一個實例,並提供一個全局訪問點。
二、方式:
1.懶漢式
/**
*
* @author Kevintan
* 經典的單件模式的實現,懶漢式
* synchronized 處理多線程的同步問題。
* 缺點:降低了性能,不利於程序頻繁的調用
* 適用場景:性能對應用程序不是很關鍵。
*/
public class Singleton1 {
private static Singleton1 uniqueInstance ;
private Singleton1() {}
public static synchronized Singleton1 getInstance(){
if (uniqueInstance == null) {
uniqueInstance = new Singleton1();
}
return uniqueInstance;
}
}
2.餓漢式
/**
*
* @author Kevintan
* 急切實例化,餓漢式
* 適用於:應用程序總是創建並使用單件實例或創建和運行時的負擔不太繁重。
* 缺點:不能用於頻繁創建或使用或耗費內存過大的程序中。
*/
public class Singleton2 {
private static Singleton2 uniqueInstance = new Singleton2();
private Singleton2() {}
public static Singleton2 getInstance(){
if (uniqueInstance == null) {
uniqueInstance = new Singleton2();
}
return uniqueInstance;
}
}
3.雙重檢索加鎖
/**
*
* @author Kevintan
*雙重檢索加鎖
*原理:首先檢查是否實例已經創建了,如果尚未創建,“才”進行同步。
*這樣一來,只有第一次創建實例時會同步。
*優點及適用於:幫助你大大減少時間耗費,提高性能
*/
public class Singleton3 {
private static volatile Singleton3 uniqueInstance ;
private Singleton3() {}
public static synchronized Singleton3 getInstance(){
if (uniqueInstance == null) {
synchronized (Singleton3.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton3();
}
}
}
return uniqueInstance;
}
}