單例模式

單例模式的實現

package singleton;


/**
 * 餓漢式
 * @author lenovo
 *
 */
public final class Singleton {
	
	private byte data[] =new byte[1024];
	private static Singleton s = new Singleton();
	private Singleton(){
		
	}
	public static Singleton gets() {
		return s;
	}
	

}

package singleton;

/**
 * 懶漢式
 * 多線程環境下無法保證單例的唯一性
 * @author lenovo
 *
 */
public final class LazySingleton {
	private byte[] data= new byte[1024];
	
	private static LazySingleton s =null;
	
	private LazySingleton() {
		
	}
	
	public static LazySingleton gets() {
		if(null==s) {
			s= new LazySingleton();
		}
		return s;
	}

}

package singleton;

/**
 * 懶漢式加同步方法
 * @author lenovo
 *
 */
public class Singleton3 {
	private byte[] data= new byte[1024];
	
	private static Singleton3 s =null;
	
	private Singleton3() {
		
	}
	
	public static synchronized Singleton3 gets() {
		if(null==s) {
			s= new Singleton3();
		}
		return s;
	}
}

package singleton;

/**
 * double-check方法
 * 首次初始化時加鎖
 * 可能會發生初始化異常
 * @author lenovo
 *
 */
public class Singleton4 {
    private byte[] data= new byte[1024];
	
	private static Singleton4 s =null;
	
	private Singleton4() {
		
	}
	
	public static  Singleton4 gets() {
		
		if(null==s) {
			synchronized(Singleton4.class) {
				if(null==s)
				s= new Singleton4();
			}
			
		}
		return s;
	}
}

package singleton;

public class Singleton5 {
   private byte[] data= new byte[1024];
	
	private static volatile Singleton5 s =null;
	
	private Singleton5() {
		
	}
	
	public static  Singleton5 gets() {
		
		if(null==s) {
			synchronized(Singleton5.class) {
				if(null==s)
				s= new Singleton5();
			}
			
		}
		return s;
	}
}

package singleton;

/**
 * holder 
 * 藉助類加載的特點
 * @author lenovo
 *
 */
public class Singleton6 {
	   private byte[] data= new byte[1024];
		
		
		private Singleton6() {
			
		}
		/**
		 * 在靜態內部類中進行直接初始化
		 * @author lenovo
		 *
		 */
		private static class Holder{
			private static volatile Singleton6 s =new Singleton6();
			
		}
		
		public static  Singleton6 gets() {
		  return Holder.s;
		}
}

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