`

【设计模式】单例模式

 
阅读更多

* 一些场景需要确保只有唯一的对象存在,如:线程池、网络连接、缓存等

 

package pattern.singleton;

//饥饿式-多线程环境下仍然安全
public class Eager {
	public static Eager instance = new Eager();
	
	private Eager(){}
	
	public static Eager getInstance() {
		return instance;
	}
}

//懒汉式-多线程环境下:每次方法调用都需要同步
class Lazy {
	public static Lazy instance;
	
	private Lazy() {}
	
	public static synchronized Lazy getInstance() {
		if(instance == null)
			instance = new Lazy();
		return instance;
	}
}

//懒汉式-多线程环境下:可减少同步次数
class LazyDoubleCheck {
	public static volatile LazyDoubleCheck instance;
	
	private LazyDoubleCheck() {}
	
	public static LazyDoubleCheck getInstance() {
		if(instance == null) {
			synchronized (LazyDoubleCheck.class) {
				if(instance == null)
					instance = new LazyDoubleCheck();
			}
		}
		return instance;
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics