0
点赞
收藏
分享

微信扫一扫

前端使用pdf.js进行pdf文件预览的第二种方式:Viewer.html

卿卿如梦 2024-02-06 阅读 11

目录

什么是单例模式

单例模式的优点 

创建单例模式的三大要点 

单例模式的实现方式

饿汉模式 

懒汉模式

使用场景


什么是单例模式

单例模式的优点 

创建单例模式的三大要点 

单例模式的实现方式

饿汉模式 

//饿汉模式:在类加载的时候就创建实例,可能会没有使用而造成资源浪费
public class Singleton_e {
//    私有的静态实例变量
    private static final Singleton_e instance=new Singleton_e();
    private Singleton_e(){
//        私有的构造方法
    }
//    公有的静态访问方法
    public static Singleton_e getInstance(){
        return instance;
    }
}

懒汉模式

public class Singleton_l {
//     懒汉模式:在请求实例的时候才会创建
//    私有的静态变量
    private static Singleton_l instance;
//    私有的构造方法
    private Singleton_l(){

    }
//    公有的静态方法
//    使用双重校验锁来确保线程安全
    public static Singleton_l getInstance(){
        if(instance==null){
            synchronized (Singleton_l.class){
                if(instance==null){
                    return new Singleton_l();
                }
            }
        }
        return instance;
    }
}

使用场景

举报

相关推荐

0 条评论