• 单例模式


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

    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;

    }
    }

  • 相关阅读:
    IOS学习计划
    IOS学习计划
    Android 多线程注意事项
    Android BroadcastReceiver 的简单实现
    新书《iOS编程(第6版)》抢鲜试读
    Apple Watch 2.0 数据通讯
    iOS 9 新特性
    Apple Watch 1.0 开发介绍 2.1 WatchKit Apps UI要点
    Apple Watch 1.0 开发介绍 1.4 简介 使用iOS技术
    Apple Watch 1.0 开发介绍 1.3 简介 WatchKit App 架构
  • 原文地址:https://www.cnblogs.com/sort/p/8324799.html
Copyright © 2020-2023  润新知