【设计模式】单例模式

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

 

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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值