1. 程式人生 > >5種單例模式

5種單例模式


/**
 * 懶漢單例模式
 */
public class Singleton_1 {
 
	private static Singleton_1 uniqueSingleton;
	
	private Singleton_1 () {}
	
	public static Singleton_1 getInstance() {
		if (null == uniqueSingleton) {
			uniqueSingleton = new Singleton_1();
		}
		return uniqueSingleton;
	}
 
}

 
/**
 * 同步單例模式
 */
public class Singleton_2 {
 
	private static Singleton_2 uniqueSingleton;
	
	private Singleton_2() {}
	
	public static synchronized Singleton_2 getInstance() {
		if (null == uniqueSingleton) {
			uniqueSingleton = new Singleton_2();
		}
		return uniqueSingleton;
	}
	
}


/**
 * 餓漢單利模式
 */
public class Singleton_4 {
	
	private static Singleton_4 uniqueSingleton = new Singleton_4();
 
	private Singleton_4() {}
	
	public static Singleton_4 getInstance() {
		return uniqueSingleton;
	}
	
}



 
public enum Singleton_5 {
	INSTANCE;
 
	private SingletonBean uniqueSingleton;
	
	private Singleton_5() {
		uniqueSingleton = new SingletonBean ();
	}
	
	public SingletonBean getInstance() {
        return uniqueSingleton;
    }
}
public class SingletonBean {
 
}


/**
 * 雙重檢查鎖單利模式
 */
public class Singleton_3 {
	
	private volatile static Singleton_3 uniqueSingleton;
 
	private Singleton_3() {}
	
	public static Singleton_3 getInstance() {
		if (null == uniqueSingleton) {
			synchronized (Singleton_3.class) {
				if (null == uniqueSingleton) {
					uniqueSingleton = new Singleton_3();
				}
			}
		}
		return uniqueSingleton;
	}
 
}



/**
 * 測試單例模式
 */
public class SingletonTest {
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Singleton_1 instance1_1= Singleton_1.getInstance();
		Singleton_1 instance1_2= Singleton_1.getInstance();
		System.out.println(instance1_1 == instance1_2);
 
		Singleton_2 instance2_1= Singleton_2.getInstance();
		Singleton_2 instance2_2= Singleton_2.getInstance();
		System.out.println(instance2_1 == instance2_2);
		
		Singleton_3 instance3_1= Singleton_3.getInstance();
		Singleton_3 instance3_2= Singleton_3.getInstance();
		System.out.println(instance3_1 == instance3_2);
		
		Singleton_4 instance4_1= Singleton_4.getInstance();
		Singleton_4 instance4_2= Singleton_4.getInstance();
		System.out.println(instance4_1 == instance4_2);
		
		SingletonBean instance5_1= Singleton_5.INSTANCE.getInstance();
		SingletonBean instance5_2= Singleton_5.INSTANCE.getInstance();
		System.out.println(instance5_1 == instance5_2);
		
	}
 
}