五种单例模式

本章提供五种单例模式

一 饿汉式

  • 类加载到内存后,就实例化一个单例,JVM保证线程安全
  • 唯一缺点:不管用到与否,类装载时就完成实例化
public class SingletonModel1 {


    private static final SingletonModel1 singletonModel1 = new SingletonModel1();

    private SingletonModel1(){}


    public static SingletonModel1 getSingletonModel1(){
        return singletonModel1;
    }


}
二 懒汉式
  • 项目启动时不加载,只有在调用的时候才加载
  • 锁加在方法上,效率略低
public class SingletonModel2 {


    private static SingletonModel2 singletoModel2 = null;


    private SingletonModel2(){}

    public static synchronized SingletonModel2 getSingletoModel2(){

        if(singletoModel2 == null){

            singletoModel2 = new SingletonModel2();
        }

        return singletoModel2;
    }
}
三 懒汉式–CAS
  • 锁不加在方法上,提高性能
  • 采用CAS方法保证线程安全
  • 采用volatile 保证 多线程可见 和 指令不会重排序,
public class SingletonModel3 {


    private static volatile SingletonModel3 singletonModel3 = null;


    private SingletonModel3() {
    }

    public static SingletonModel3 getSingletoModel3() {


        if (singletonModel3 == null) {

            synchronized (SingletonModel3.class) {

                if (singletonModel3 == null) {

                    singletonModel3 = new SingletonModel3();
                }
            }
        }
        return singletonModel3;
    }
}
四 内部类
  • 静态内部类
  • 加载外部类时不会加载内部类,这样可以实现懒加载
  • JVM保证单例
public class SingletonModel4 {


    private SingletonModel4() {
    }

    private static class singletonHolder{

        private final static SingletonModel4 singletonModel4 = new SingletonModel4();
    }


    public static SingletonModel4 getSingletoModel4() {

        return singletonHolder.singletonModel4;
    }
}
五 枚举
  • 枚举方式
  • 不仅可以解决线程同步,还可以防止反序列化。
public enum SingletonEnum5 {

    SINGLETON;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值