`

设计模式之——靠谱的单例模式

阅读更多
修改了一下,还是推一下吧,以前工作中见过很多单例都是存在些问题的单例
虽然简单,但是能够写正确的真没大见过
/**
 * 靠谱的单例模式
 * 
 * @author john
 *
 */
public class Singleton {
	/**
	 * volatile:确保初始化 Singleton 多线程 正确处理
	 */
	private volatile static Singleton uniqueInstance;

	/**
	 * private 修饰构造方法,只有当前类能够初始化该对象
	 */
	private Singleton() {

	}

	/**
	 * 两次非空判断
	 * 
	 * @return
	 */
	public static Singleton getInstance() {
		if (uniqueInstance == null) {
			synchronized (Singleton.class) {
				if (uniqueInstance == null) {
					uniqueInstance = new Singleton();
				}
			}
		}

		return uniqueInstance;
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics