饿汉式单例类

2020-03-30  本文已影响0人  今天也要努力呀y

单例类

public class EagerSingleton {
    //在类加载时就完成了初始化,所以类加载较慢,但获取对象速度快
    private static EagerSingleton instance = new EagerSingleton();

    //私有构造方法,所以不能实例化
    private EagerSingleton(){}

    //因为不能实例化,所以为public static类型
    public static EagerSingleton getInstance(){
        return instance;
    }

    //实例化调用
    public void test(){
        System.out.println("只有一个实例在运行");
    }

}

测试类

public class SingletonTest {
    public static void main(String[] args) {
        EagerSingleton es1 = EagerSingleton.getInstance();
        es1.test();
        EagerSingleton es2 = EagerSingleton.getInstance();
        es2.test();

        //写法错误,因为构造方法是私有的,所有不能创建
        //EagerSingleton es3 = new EagerSingleton();

        //为了验证只有一个实例
        System.out.println(es1==es2);
    }
}

输出

只有一个实例在运行
只有一个实例在运行
true
上一篇 下一篇

猜你喜欢

热点阅读