单例模式




package singleton;

/**
 * @author 丛培雪 E-mail:[email protected]
 * @version 创建时间:2008-7-6 上午02:21:41 类说明
 */
public class Singleton {
	static class SingletonHolder {
		static Singleton instance = new Singleton();
	}

	public static Singleton getInstance() {
		return SingletonHolder.instance;
	}
}







	package singleton;
	
	/**
	 * @author 丛培雪 E-mail:[email protected]
	 * @version 创建时间:2008-7-6 上午02:00:50 类说明
	 */
	public class Singleton1 {
		private Singleton1() {
		}
	
		private static Singleton1 instance = new Singleton1();
	
		public static Singleton1 getInstance() {
			return instance;
		}
	}






package singleton;

/**
 * @author 丛培雪 E-mail:[email protected]
 * @version 创建时间:2008-7-6 上午02:03:50 类说明
 */
public class Singleton2 {
	private static Singleton2 instance = null;
	private static int hasInitialized=0; 
	private Singleton2() {
	}

	public static Singleton2 getInstance() {
		if(hasInitialized==0){
			synchronized(Singleton2.class){  
				if(hasInitialized==0){
					instance=new Singleton2();   
			        hasInitialized=1; 
				}
			}
		}
		return instance;
	}
}


你可能感兴趣的:(java)