如何以正确的方式写一个单身人士?

如何以正确的方式写一个单身人士?

问题描述:

今天在采访中,一位采访者要求我写一个Singleton课。我给了我答案

Today in my interview one interviewer asked me to write a Singleton class. And i gave my answer as

public class Singleton {

    private static Singleton ref;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (ref == null) {
            ref = new Singleton();
        }
        return ref;
    }
}

突然他告诉我这是旧的写作方式类。任何一个请帮助我,为什么他这样说。

suddenly he told me this is old way of writing the class. Can any one please help me why he told like that.

创建单例时我想到的第一件事是枚举。我通常使用枚举来实现单例:

The first thing which comes to my mind when creating a singleton is enum. I generally use enum to implement singleton:

enum Singleton {
    INSTANCE;
}

使用枚举获得的一个好处是使用序列化。

One benefit you get with using enum is with Serialization.

使用单例类,您必须确保序列化和反序列化不会通过实现 readResolve()方法,而枚举不是这样。

With singleton class, you would have to make sure that serialization and deserialization doesn't create a new instance by implementing the readResolve() method, while this is not the case with enum.

使用类,您应该像这样创建单例:

Using class you should create the singleton like this:

public final class Singleton implements Serializable {
    // For lazy-laoding (if only you want)
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    private Singleton() {
        if (SingletonHolder.INSTANCE != null) {
            // throw Some Exception
        }
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    // To avoid deserialization create new instance
    @SuppressWarnings("unused")
    private Singleton readResolve() {
        return SingletonHolder.INSTANCE;
    }
}