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

查看:89
本文介绍了在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天全站免登陆