zoukankan      html  css  js  c++  java
  • 单例模式

    /*
    * 懒汉式单例模式(安全效率低)
    */

    public class LazySingleton {

    private static LazySingleton instance=null;

    //私有构造器
    private LazySingleton() {}

    public static synchronized LazySingleton getInstance() {

    if(instance==null) {
    instance=new LazySingleton();
    }

    return instance;
    }

    }

    /*
    * 饿汉式单例模式(不安全,效率高)
    */
    public class EagerSingleton {

    //私有构造器
    private EagerSingleton() {}

    private static EagerSingleton instance=new EagerSingleton();

    public static EagerSingleton getInstance() {

    return instance;

    }

    }

    /*
    * 双重检查加锁
    * 所谓双重加锁机制,指的是:并不是每次进入getInstance方法都需要同步,而是先不同步,进入方法后,
    * 先检查实例是否存在,如果不存在才进行下面的同步块,这是第一重检查,进入同步块过后,再次检查实例是否
    * 存在,如果不存在,就在同步的情况下创建一个实例,这是第二次检查。这样以来,只需要同步一次了,进而提高
    * 了效率。
    */

    public class SynthesizeSinleton {

    private volatile static SynthesizeSinleton instance=null;

    private SynthesizeSinleton() {}

    public static SynthesizeSinleton getInstance() {

    //先检查实例是否存在,如果不存在才进行下面语句
    if(instance==null) {

    //同步块,线程安全的创建实例
    synchronized (SynthesizeSinleton.class) {

    //第二次实例是否存在,如果不存在才真正的创建实例
    if(instance==null) {

    instance =new SynthesizeSinleton();
    }
    }
    }

    return instance;

    }
    }

  • 相关阅读:
    Vue3.0 是如何变得更快的?
    阿里云 Centos7 安装mongodb
    ASP.Net Core5.0 EF Core使用记录
    MongoDB批量更新|按条件更新SQL|批量删除某个字段
    Layui单元格编辑获取修改前的值
    判断字符串出现的多个位置
    原生JavaScript的DOM操作汇总
    @Value值为null、#和$的区别
    Dubbo推荐用法
    Dubbo 服务化最佳实践
  • 原文地址:https://www.cnblogs.com/sort/p/8324799.html
Copyright © 2011-2022 走看看