單例模式:
有一些對象我們只希望有一個,例如線程池、緩存、日誌對象等。這個時候就可以用到單利模式,單例可以確保一個類只有一個實例,並且提供一個全局訪問點。
常見的單例:
1. 經典的單例:
/** * Created on 2016/11/15. * 經典單利模式 */ public class Person1 { private static Person1 person1; private Person1(){} public static Person1 getInstance(){ if(person1 == null){ person1 = new Person1(); } return person1; } }2. 解決多線程問題的單例:
/** * Created on 2016/11/15. * 多線程單利模式 */ public class Person2 { private static Person2 person2; private Person2(){} //缺點:同步方法會大大降低程序的執行效率 public static synchronized Person2 getInstance(){ if(person2 == null){ person2 = new Person2(); } return person2; } }3. 急切用到,並且使用頻繁使用到這個對象的實例:
/** * Created on 2016/11/15. * "急切"創建實例 */ public class Person3 { //適用於頻繁創建使用單利的情況 private static Person3 person3 = new Person3(); private Person3(){} public static Person3 getInstance(){ return person3; } }4. 雙重驗證:
/** * Created on 2016/11/15. * "雙重"創建模式:推薦這種方式(java1.4以上) */ public class Person4 { /** * volatitle關鍵字:當person4被實例化之後,多線程能正確的使用處理person4 * 不適用於1.4及更早的java中 */ private volatile static Person4 person4; private Person4(){} /** * 如果沒有創建才同步,這樣只有第一次創建才進行同步 */ public static Person4 getInstance(){ if(person4 == null){ synchronized (Person4.class){ if(person4 == null){ person4 = new Person4(); } } } return person4; } }