浅谈单例模式的4种写法

单例模式
一个类只能产生一个对象就叫做单例模式
如果编写单例模式:
1.构造器私有
2.对外提供获取对象的方法
3.声明一个static成员变量 类加载的时候创建当前对象
4.在获取方法的时候放回成员变量的值

饿汉式:
优点:天然线程安全
缺点:不能做到延迟加载

public class Single {
// 声明一个Single对象
public static Single single = new Single();
//1:将构造器私有
private Single() {
}

public static Single getInstance() {
	return single;
}
public static void add() {
}
}

懒汉式:
​优点:可以做到延迟加载
缺点:线程不安全

public class Lazy {
private static Lazy lazy = null;
private Lazy() {
	
}

public static Lazy getInstance() {
	if(lazy==null) {
		lazy = new Lazy();
	}
	return lazy;
}
}

同步的懒汉式(线程安全,可用,不建议使用)
缺点:第一次加载时反应稍慢,每次调用 getInstance 都进行同步,造成不必要的同步开销,这种模式一般不建议使用。

public class Lazy {
private Lazy() {
}

private static Lazy Singleton singleton=null;

public synchronized static Singleton getInstance() {
    if (Singleton == null) {
        singleton = new Singleton();
    }
    return singleton;
}
}

双重检查锁 DCL (线程安全,大多数场景满足需求,推荐使用)
优点:资源利用率高,第一次执行getInstance时单例对象才会被实例化,效率高。
缺点:第一次加载时反应稍慢,也由于Java内存模型的原因偶尔会失败。在高并发环境下也有一定的缺陷,虽然发生的概率很小。

public class Singleton {
private Singleton() {
}
private static volatile Singleton singleton;

public static Singleton getInstance() {
    if (singleton == null) {
        synchronized (Singleton.class) {
            // 未初始化,则初始instance变量
            if (singleton == null) {
                singleton = new Singleton();
            }
        }
    }
    return singleton;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值