单例模式

单例模式

作用

保证在应用程序中最多只能有一个实例

优点

  • 提升运行效率
  • 实现数据共享,案例:application对象

延迟加载(懒汉式)

public class Singleton{
    // 私有化属性,防止通过类名直接调用
    private static Singleton singleton;
    
    // 私有化构造方法,防止其他类实例化这个对象
    private Singleton(){}
    
    // 对外提供的访问入口
    public static Singleton getInstance(){
        // 如果实例化过,直接返回
        if(singleton == null){
            // 多线程情况下,可能会出现if同时成立的情况
            // 解决方案:添加锁,但是由于添加了锁,会导致执行效率变低
            synchronized(Singleton.class){
                // 双重验证
                if(singleton == null){
                    sington = new Singleton();
                }
            }
        }
        return singleton;
    }
}

立即加载(饿汉式)

解决了懒汉式中多线程访问可能出现同一个对象和效率低的问题

public class Singleton{
    // 在类进行加载时进行实例化
    private static Singleton singleton = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return singleton;
    }
}
posted @ 2019-09-09 12:52  Chauncey-Leonard  阅读(147)  评论(0)    收藏  举报