欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单例模式-饿汉与懒汉式

程序员文章站 2022-07-14 09:39:14
...
package Java0908;

public class TestSingleton {
    public static void main(String[] args) {
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();

        System.out.println(instance == instance1);

        HungerSingleton singleton = HungerSingleton.getSingleton();
        HungerSingleton singleton1 = HungerSingleton.getSingleton();
        System.out.println(singleton == singleton1);


    }

}

//饿汉式
class Singleton {

    //2、在类的内部创建对象
    private static Singleton instance = new Singleton();

    //1、构造器私有化
    private Singleton() {

    }

    //3、提供公共的get方法
    public static Singleton getInstance() {
        return instance;
    }

}


//懒汉式
class HungerSingleton {

    //1、私有化构造器
    private HungerSingleton() {
    }

    //2、在类的内部创建对象
    private static HungerSingleton singleton = null;

    //3、提供公共的get方法
    public static HungerSingleton getSingleton() {
        if (singleton == null) {
            singleton = new HungerSingleton();
        }

        return singleton;

    }


}