单例模式

饿汉模式

  • 优点: 没有任何锁,利用类的静态成员只能被加载一次的特点,保证了实例了唯一性,效率高。
  • 缺点: 加载类时就已经产生了实例(调用getInstance前),占用资源比较多。
public class Singleton {
    private Singleton() {
        System.out.println("s1");
    }

    private static final Singleton singleton = new Singleton();

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

懒汉模式

延迟加载,但是线程不安全,只适合单线程应用。

public class Singleton {
    private Singleton() {
        System.out.println("s2");
    }

    private static Singleton singleton = null;

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

双重锁模式

又重锁保证线程安全,但性能上会有所牺牲。

public class Singleton {
    private Singleton() {
        System.out.println("s3");
    }

    private volatile static Singleton singleton = null;

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

静态内部类模式

加载一个类时,其内部类不会被同时加载,从而保证了其延时加载,同时利用static保证了实例的单一性。

public class Singleton {
    private Singleton() {
        System.out.println("s4");
    }

    private volatile static Singleton singleton = null;

    public static Singleton getInstance(){
        return LazySingleton.lazyInstance;
    }

    private static class LazySingleton{
        private static final Singleton lazyInstance = new Singleton();
    }
}

示例代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值