Java单例模式实现方式汇总

饿汉式

public class Singleton {

    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

还有一个变种:静态代码块式

public class Singleton {

    private static Singleton instance;

    static {
        instance = new Singleton();
    }

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

缺点:没有懒加载。如果没有用到这个单例。造成浪费。


懒汉式

public class Singleton {

    private static Singleton instance;

    private Singleton() {}

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

缺点:虽然有了懒加载,但只能在单线程中使用。

如果要在多线程中使用,就要同步。但是效率太低了。

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

双重校验

public class Singleton {

    private static volatile Singleton instance;

    private Singleton() {}

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

缺点:由于有序性问题,还是有问题。详细如下:

instance = new Singleton();这条语句不是原子的。需要做下面操作:

  1. 分配内存空间
  2. 初始化对象
  3. 内存地址指向instance

因为有指令重排的优化,步骤2和3可能颠倒。从而出现空指针问题。

所以千万不要忘了加volatile。防止指定重排。


静态内部类

public class Singleton {

    private Singleton() {}

    private static class SingletonInstance {
        private static final Singleton singleton = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonInstance.singleton;
    }
}

类装载机制保证线程安全性。比双重检查简单多了。

但是又要考虑新的问题了,不能防止反序列化方式,生成多个对象。


枚举方式

public enum Singleton {
    INSTANCE;
    Singleton() {}
    public void getName() {}
}

线程安全的同时,还有防止反序列化生成多个对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

独立开发大本事

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值