手撕单例模式-饿汉式

单例模式

应用场景:只需要一个实例的时候使用

1、第一种写法

饿汉式:

  • 类加载到内存后,就实例一个单例,JVM保证线程安全
  • 优点:简单实用
  • 缺点:不管你用还是不用,只要类装载时就完成实例化了
public class Singleton {
    // 使用final必须初始化
    private static final Singleton INSTANCE = new Singleton();
    /**
     * 把构造方法设置成私有的,这样new不了
     * 想要使用,怎么做呢?我们提供一个public方法getInstance进行调用
     */
    private Singleton() {}
    public static Singleton getInstance() {
        //不管你调用多少次getInstance,我永远只有一个INSTANCE = new Mgr01(
        return INSTANCE;
    }

    //证明是同一个实例
    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance1 == instance);//如果返回true说明同一个实现
    }
}

更多文章已经被GitHub收录以及电子书等资料:https://github.com/niutongg/JavaLeague

上一篇:mac vscode 下载安装与配置


下一篇:1.5.1. The Singleton Scope (单例作用域)