Java单例模式的三种实现方式

单例模式之饿汉式

在类加载时就初始化一个类对象,使用静态加载,但是在类加载时就实例化对象,单例对象较大的时候会影响系统加载速度。

public class Singleton {

    private Singleton() {
        System.out.println("This is constructor.");
    }

    private static Singleton instance = new Singleton();

    public static Singleton getInstance () {
        return instance;
    }

    public static void main(String[] args) {
        Singleton.getInstance();
    }
}

延迟加载的singleton

只有在访问到单例对象的时候才去检查和实例化单例对象,满足延迟加载,但多线程访问时需要加线程同步,影响访问效率


public class LazySingleton {

    private LazySingleton() {}
    private static LazySingleton instance ;

    public synchronized static LazySingleton getInstance () { //对于多线程访问的需加synchronized
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }

}

使用静态内部类来作为singleton的容器

既能延迟加载,又能保证线程安全


public class StaticSingleton {

    private StaticSingleton() {}
    private static class SingletonHolder { //私有内部类在StaticSingleton 加载时,不初始化
        private static StaticSingleton instance = new StaticSingleton();
    }

    public static StaticSingleton getInstance () {
        return SingletonHolder.instance;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值