在Java枚举中的INSTANCE [英] INSTANCE in a Java Enum

查看:1119
本文介绍了在Java枚举中的INSTANCE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在枚举中定义INSTANCE是一个很好的做法,为了免费序列化(有效Java Edition 2,项目3)的好处。如果有人可以解释一下它的意思,那将是很棒的。

It is a good practices to define INSTANCE in an Enum, for the benefit of serialization for free (Effective Java Edition 2, Item 3). If anyone could explain a bit more what it means, it will be great.

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

提前感谢
Lin

thanks in advance, Lin

推荐答案

这是一个演示: / p>

Here's a demonstration:

import java.io.*;

class ClassSingleton implements Serializable {
    public static final ClassSingleton INSTANCE = new ClassSingleton();

    private ClassSingleton() {}
}

enum EnumSingleton {
    INSTANCE;
}

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        byte[] data;
        try (ByteArrayOutputStream output = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(output)) {
            oos.writeObject(ClassSingleton.INSTANCE);
            oos.writeObject(EnumSingleton.INSTANCE);
            data = output.toByteArray();
        }

        try (ByteArrayInputStream input = new ByteArrayInputStream(data);
             ObjectInputStream ois = new ObjectInputStream(input)) {
            ClassSingleton first = (ClassSingleton) ois.readObject();
            EnumSingleton second = (EnumSingleton) ois.readObject();

            System.out.println(first == ClassSingleton.INSTANCE);
            System.out.println(second == EnumSingleton.INSTANCE);
        }
    }
}

这里我们有两个简单的基于类的单例和基于枚举的版本。

Here we have both a "simple" class-based singleton, and the enum-based version.

我们将两个实例写入一个 ObjectOutputStream ,然后再读回来。输出是 false then true ,显示使用基于类的单例,我们已经结束了 ClassSingleton 的两个实例...我们的正常实例,以及由反序列化创建的一个。然而,我们只有一个 EnumSingleton 的实例,因为枚举具有序列化/反序列化代码来保留其固定值集的性质。你也可以为基于类的单身人士编写这段代码,但是更容易不必。

We write out both instances to an ObjectOutputStream, then read them back again. The output is false then true, showing that with the class-based singleton, we've ended up with two instances of ClassSingleton... our "normal" one, and the one created by deserialization. We only have one instance of EnumSingleton however, because enums have serialization/deserialization code to preserve their "fixed set of values" nature. You can write this code for the class-based singleton too, but it's easier not to have to.

这篇关于在Java枚举中的INSTANCE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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