單例設(shè)計模式(Singleton Pattern):是指確保某個類只有一個實例屋摇,而且自行實例化并向整個系統(tǒng)提供這個實例羞迷。需要注意的是猴凹,在系統(tǒng)中只有真正有“單一實例”的需求時才可以使用揽思。
單例使用的三個要點:
(1)某個類只能有一個實例悉抵;
(2)該類必須自行創(chuàng)建這個實例肩狂;
(3)該類必須自行向整個系統(tǒng)提供這個實例。
下面我會介紹幾種常用的單例模式姥饰。
1傻谁、餓漢式
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
不管用到與否類裝載時就完成了實例化,所以如果在程序中沒有用到就會浪費內(nèi)存媳否,但是你不用它那你寫它干嘛呢栅螟,哈哈哈哈。
2篱竭、懶漢式
public class Singleton {
private static Singleton INSTANCE;
private Singleton () {}
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return INSTANCE;
}
}
線程不安全
3力图、雙重同步鎖(懶漢式)
public class Singleton {
// 1. 用volatile關(guān)鍵詞是為了防止JVM中執(zhí)行時指令重排序
private static volatile Singleton INSTANCE;
private Singleton() {}
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized(Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}
4、Holder式(懶漢式)
public class Singleton {
private Singleton() {}
public statice Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
5掺逼、枚舉單例
public class Singleton {
INSTANCE;
public static Singleton getInstance() {
return INSTANCE;
}
}