ITeye博客

设计模式之单例模式

从百草园到三味书屋 · 2013-01-18 17:19 · pattern · 编程语言 · Markdown

package singleton;

public class Singleton {

	
}

/**
 * 适用于单线程环境
 *
 * @author  
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonOne{
	
	private static SingletonOne instance = null;
	
	private SingletonOne(){}
	
	public static SingletonOne getInstance(){
		if(instance==null){
			instance = new SingletonOne();
		}
		return instance;
	}
}

/**
 * 适用于多线程环境,但是该同步机制会对性能造成一定的下降
 *
 * @author  meiquan_yang
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonTwo{
	
	private static SingletonTwo instance = null;
	
	private SingletonTwo(){}
	
	public static synchronized SingletonTwo getInstance(){
		if(instance==null){
			instance = new SingletonTwo();
		}
		return instance;
	}
	
}

/**
 * 适用于多线程环境,采用Double-check Locking方式检测,只有在第一次实例化的时候才进入同步块,
 * 为了保证内存可见性,instance最好加上volatile关键字。
 *
 * @author  meiquan_yang
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonThree{
	
	private static volatile SingletonThree instance = null;
	
	private SingletonThree(){
		//...
	}
	
	public static SingletonThree getInstance(){
		if(instance==null){
			synchronized (SingletonThree.class) {
				if(instance==null){
					instance = new SingletonThree();
				}
			}
		}
		return instance;
	}
}

/**
 * 即是延迟加载,又能保证多线程环境下单例。
 *
 * @author  meiquan_yang
 * @since   Pattern 1.0.0
 * @created 2013-1-6
 */
class SingletonFour{
	
	private static class SingletonHolder{
		private final static SingletonFour instance = new SingletonFour();
	}
	
	private SingletonFour(){}
	
	public static SingletonFour getInstance(){
		return SingletonHolder.instance;
	}
}



评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。