单例模式

单例模式的特点:

  1. 一个类只能有一个实例
  2. 类自己创建这个实例
  3. 整个系统都共同使用这个实例

单例模式分为:

  1. 懒汉式:类一加载就创建对象,上来就new一个不可修改的类对象,再来一个空的私有构造方法,和一个公有的入口(返回值是类对象)
  2. 饿汉式:用的时候,才去创建对象,声明一个为空的对象,在调用时new一个新的对象

以上两种情况在多线程下是不安全的,因为new对象是非原子性的,重排序问题会造成多线程下不安全

1.饿汉模式

class Singleton {
	private static Singleton instance = new Singleton();
	private Singleton() {}
	public static Singleton getInstance() {
		return instance;
	}
}

2.懒汉模式-单线程版

class Singleton {
	private static Singleton instance = null;
	private Singleton() {}
	public static Singleton getInstance() {
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

3.懒汉模式-多线程版-性能低

class Singleton {
	private static Singleton instance = null;
	private Singleton() {}
	public synchronized static Singleton getInstance() {
		if (instance == null) {
		instance = new Singleton();
		}
		return instance;
	}
}

4.懒汉模式-多线程版-二次判断-性能高

class Singleton {
	private static volatile Singleton instance = null;
	private Singleton() {}
	public static Singleton getInstance() {
		if (instance == null) {
			synchronized (Singleton.class) {
				if (instance == null) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值