在 Java 中使用 Enum 作为单例的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/427902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:30:34  来源:igfitidea点击:

What is the best approach for using an Enum as a singleton in Java?

javasingleton

提问by Miles D

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)

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

public enum Elvis {
    INSTANCE;
    private int age;

    public int getAge() {
        return age;
    }
}

and then calling Elvis.INSTANCE.getAge()

然后打电话 Elvis.INSTANCE.getAge()

and

public enum Elvis {
    INSTANCE;
    private int age;

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

and then calling Elvis.getAge()

然后打电话 Elvis.getAge()

采纳答案by Jon Skeet

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).

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

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

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

回答by Tom Hawtin - tackline

(Stateful) Singletons are generally used to pretend not to be using static variables. If you don't actually use the publicly static variable then you will fool less people.

(有状态的)单例通常用于假装不使用静态变量。如果您实际上不使用公共静态变量,那么您将愚弄的人更少。

回答by Nicolas

A great advantage is when your singleton must implements an interface. Following your example:

一个很大的优势是当你的单例必须实现一个接口时。按照你的例子:

public enum Elvis implements HasAge {
    INSTANCE;
    private int age;

    @Override
    public int getAge() {
        return age;
    }
}

With:

和:

public interface HasAge {
    public int getAge();
}

It can't be done with statics...

它不能用静态来完成......

回答by Peter Lawrey

I would choose the option which is the simplest and clearest. This is somewhat subjective, but if you don't know what is clearest, just go for the shortest option.

我会选择最简单、最清晰的选项。这有点主观,但如果你不知道什么是最清楚的,那就选择最短的选项。