单例模式 饿汉式

静态变量

class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {
    }

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

静态代码块

class Singleton {
    private Singleton() {
    }

    private static final Singleton instance;

    static {
        instance = new Singleton();
    }

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

 

posted on 2022-04-14 11:40  金满仓  阅读(20)  评论(0编辑  收藏  举报

导航