在 Java 中使用 Enum 作为单例的最佳方法是什么? [英] What is the best approach for using an Enum as a singleton in Java?

查看:22
本文介绍了在 Java 中使用 Enum 作为单例的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

建立在 SO 问题 Java 中的最佳单例实现 -即关于使用枚举创建单例 - 之间有什么区别/优点/缺点(省略构造函数)

Building on what has been written in SO question Best Singleton Implementation In Java - namely about using an enum to create a singleton - what are the differences/pros/cons between (constructor omitted)

public enum Elvis {
    INSTANCE;
    private int age;

    public int getAge() {
        return age;
    }
}

然后调用Elvis.INSTANCE.getAge()

public enum Elvis {
    INSTANCE;
    private int age;

    public static int getAge() {
        return INSTANCE.age;
    }
}

然后调用Elvis.getAge()

推荐答案

假设您要绑定的东西将使用它所给定的任何对象的属性 - 您可以很容易地传递 Elvis.INSTANCE,但不能传递Elvis.class 并期望它找到属性(除非故意编码以查找类的静态属性).

Suppose you're binding to something which will use the properties of any object it's given - you can pass Elvis.INSTANCE very easily, but you can't pass Elvis.class and expect it to find the property (unless it's deliberately coded to find static properties of classes).

基本上,当您想要一个实例时,您只使用单例模式.如果静态方法对你来说没问题,那么就使用它们,不要打扰枚举.

Basically you only use the singleton pattern when you want an instance. If static methods work okay for you, then just use those and don't bother with the enum.

这篇关于在 Java 中使用 Enum 作为单例的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆