Is the Enum plural still singleton?

It is well known that one of the best ways to implement singleton is to use Enumone made by the popular Josh Bloch .

He claims:

This approach is functionally equivalent to the open-source field approach, except that it is more concise, provides free serialization techniques and provides an excellent guarantee against multiple instances even in the face of complex serialization or reflection attacks. Although this approach has not yet been adopted, a singleton enumeration type is the best way to implement a singleton.

Is it used for multi-element Enum? Will there be an instance of each element exactly once?

The intended benefit would be to have several similar but different singleton-enum, for example: each element introduces a different configuration.

Example:

public enum Beatles {

    george("George"),
    john("John"),
    paul("Paul"),
    ringo("Ringo"),
    ;

    private Beatles(final String name) {
        this.name = name;
    }
    private final String name;

    public String getName() {
        return name;
    }
}
+4
source share
2 answers

You can extend the singleton enum paradigm to support "similar but different" singletones using the marker interface:

public interface MySingletonInterface {
    void doFoo(Bar bar);
}

Then your enums can implement the interface:

public enum FirstSingletonEnum implements MySingleTonInterface {

    ...

    @Override
    public void doFoo(Bar bar) {
        ... //do something with bar
    }
}

public enum SecondSingletonEnum implements MySingleTonInterface {

    ...

    @Override
    public void doFoo(Bar bar) {
        ... //do something slightly different with Bar
    }
}

It seems to me that this is a cleaner approach that puts all implementations in one enumeration.

, . , , enum , , enum, . , , , , .

+2
enum A {INSTANCE};

class A {
    public static final A INSTANCE = new A();
}

Singleton. , Singleton, Singleton . , , .

+1

All Articles