Java-單例設計模式
阿新 • • 發佈:2020-09-09
單例模式
單執行緒
餓漢式:
public Class Singleton{
//類被載入的時候就例項化一個物件
private static Singleton singleton1 = new Singleton();
//私有的構造方法
private Singleton(){}
//以自己例項為返回值的靜態的公有方法
public static Singleton getSingleton(){
return singleton1;
}
}
懶漢式:
public Class Singleton{ private static Singleton singleton2; private Singleton(){} public static Singleton getSingleton(){ if(singleton2 == null){ singleton2 = new Singleton(); } return singleton2; } }
多執行緒
餓漢式天生執行緒安全
懶漢式保證執行緒安全的四種方法:
-
synchronized方法
public Class Singleton{ private static Singleton singleton2; private Singleton(){} public static synchronized Singleton getSingleton(){ if(singleton2 == null){ singleton2 = new Singleton(); } return singleton2; } }
-
synchronized程式碼塊
public Class Singleton{ private static Singleton singleton2; private Singleton(){} public static Singleton getSingleton(){ synchronized(Singleton.class){ if(singleton2 == null){ singleton2 = new Singleton(); } } return singleton2; } }
-
內部類
public Class Singleton{ private Singleton(){} private static Singleton Holder(){ private static singleton2 = new Singleton() ; } public static Singleton getSingleton(){ return Holder.singleton2; } }
-
雙重延遲檢測
public Class Singleton{ private static volatile Singleton singleton2; private Singleton(){} public static Singleton getSingleton(){ if(singleton2 == null){ //只在第一次new例項的時候同步 synchronized(Singleton.class){ singleton2 = new Singleton(); } } return singleton2; } }