簡單而快樂的24種設計模式之單例模式

所謂單例,就是整個程序有且僅有一個實例。該類負責創建自己的對象,同時確保只有一個對象被創建。在Java,一般常用在工具類的實現或創建對象需要消耗資源。
特點

  1. 類構造器私有
  2. 持有自己類型的屬性
  3. 對外提供獲取實例的靜態方法

單例模式的多種方式

		//最優方式:
		//1.在getInstance的方法中沒有鎖,且只有被調用的時候纔會創建Test實例
		//2.因爲內部類testContext是private,所以外部無法訪問,無法初始化
		//3.只有在調用getInstance纔會初始化這個內部類,保證線程安全
	public class Test {
		//構造方法私有
		private Test(){}
		//內部類加載
		private static class testContext{
			private static  Test instrance=new Test();
		}
		public static Test getInstance(){
			return testContext.instrance;
		}

	}
	//第二種 懶漢式 運行到再創建實例 線程不安全
	public class Test {
		//構造方法私有
		private Test(){}
		private volatile static Test testContext;
		public static Test getInstance(){
			if(testContext==null){
				testContext=new Test();
			}
		return testContext;
	}
	//第三種 餓漢式 先創建實例
	public class Test {
		//構造方法私有
		private Test(){}
		private volatile static Test testContext=new Test ();
		public static Test getInstance(){
			return testContext;
		}
	}
	//第四種 雙鎖單例
	public class Test {
		//構造方法私有
		private Test(){}
		private volatile static Test testContext;
		public static Test getInstance(){
			 if (testContext == null) {  
        		synchronized (Test .class) {  
        		if (testContext== null) {  
            	testContext= new testContext();  
        	} 
        	  return testContext;   
        }
      
    }  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章