单例模式

什么是单例模式

保证一个类仅有一个实例,对外提供一个访问方法。

为什么要用单例模式

资源控制,节省内存,资源共享,延迟初始化,易于维护

实现方式

饿汉式

public class Singleton01 {

    private static Singleton01 instance = new Singleton01();

    private Singleton01() {}

    public static Singleton01 getInstance(){
        return instance;
    }
}

懒汉式

public class Singleton02 {

    private static Singleton02 instance;

    private Singleton02() {
    }

    public static Singleton02 getInstance() {
        if (instance == null) {
            instance = new Singleton02();
        }
        return instance;
    }
}

线程安全的懒汉式

public class Singleton03 {

    private static volatile Singleton03 instance;

    private Singleton03(){}

    public static Singleton03 getInstance(){
        if(instance == null){
            synchronized(Singleton03.class){
                if(instance == null){
                    instance = new Singleton03();
                }
            }
        }
        return instance;
    }
}

枚举

public enum Singleton {
    SINGLETON;
}

参考文章:
https://blog.csdn.net/m0_63653444/article/details/140007103

posted @ 2024-10-12 23:11  zun呐  阅读(4)  评论(0)    收藏  举报