public class Singleton {
//私有的 靜態的 本類屬性
private volatile static Singleton _instance;
//私有化構造器
private Singleton() {}
/*
* 懶漢模式
*/
public static Singleton getInstance() {
if (_instance == null) {
_instance = new Singleton();
}
return _instance;
}
/*
*2 synchronized版本
*/
public static synchronized Singleton getInstanceTS() {
if (_instance == null) {
_instance = new Singleton();
}
return _instance;
}
//3.雙重檢查鎖:檢查了2次;使用了一個鎖
//此處需要volatile修飾屬性保證它的內存可見性??
public static Singleton getInstanceDC() {
if (_instance == null) {//第一次檢查
synchronized (Singleton.class) {
if (_instance == null) { //第二次檢查 //線程1創建完對象後,線程會判斷一次就不會創建對象了。解決了首次創建對象的唯一性問題。
_instance = new Singleton();
}
}
}
return _instance;
}
}
轉:https://www.cnblogs.com/paul011/p/8574650.html
根據內部類不會在其外部類被加載的同時被加載的事實,我們可以引申出單例模式的一種實現方式: 靜態內部類
Java代碼
- public class Singleton {
- private Singleton() {}
- static class SingletonHolder {
- private static final Singleton instance = new Singleton();
- }
- public static Singleton getInstance() {
- return SingletonHolder.instance;
- }
- }
該“靜態內部類”實現單例模式的方式,在單例對象佔用資源大,需要延時加載的情況下優選。