單例模式
1.餓漢模式:在類被加載的時候創建實例(線程安全的)
2.懶漢模式:在方法被運行的時候創建實例(線程不安全的) 解決方法:通過雙檢驗
餓漢模式:
public class Singleton { //餓漢模式 //將構造函數私有化 private Singleton(){ } //將對象實例化 private static Singleton instance = new Singleton(); //得到實例的方法 public static Singleton getInstance() { return instance; } }
懶漢模式:
//懶漢模式 //將構造函數私有化 private Singleton(){ } //將對象實例化 private static Singleton instance ; //得到實例的方法 public static Singleton getInstance() { if(instance == null){ instance = new Singleton(); } return instance; }
解決方法1(慢)
//得到實例的方法 synchronized public static Singleton getInstance() { if(instance == null){ instance = new Singleton(); } return instance; }
解決方法2(慢)
//得到實例的方法 public static Singleton getInstance() { synchronized (Singleton.class){ if(instance == null){ instance = new Singleton(); } return instance; } }
解決方法3(推薦)
原因:如果實例已經存在,就不存在線程安全的問題,可以直接獲取實例,減少了加鎖而造成的速度問題。
public class Singleton { //懶漢模式 //將構造函數私有化 private Singleton(){ } //將對象實例化 private static volatile Singleton instance ; //得到實例的方法 public static Singleton getInstance() { if(instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
volatile 關鍵字