Singleton enum with constants

Viewed 639

I am trying to create enum with few constants. I want the enum to be singleton. With below code, I am getting compilation error in eclipse :

Syntax error, insert ")"

to complete the method declaration at line 5. I am not able to find out whats wrong.

public enum Days {

      SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY;

      INSTANCE; // line 5

      public Days getInstance() {
        return INSTANCE;
     }
}
4 Answers

Your two requirements are incompatible. Enum values are instances of the enum class, and you want seven such values. By definition, a singleton class is a class that has a single instance:

Singleton: Ensure a class has only one instance, and provide a global point of access to it. -- Design Pattern Book - Singleton

So technically it is not possible to have an enumerated type with more than one value that is also a singleton.

For most usage scenarios, you can simply use a basic enumerated type definition:

public enum Days 
{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

The only case where it makes sense to combine the Singleton design pattern and enumerated types is when one wishes to use an enum declaration to enforce the Singleton pattern. See this post for details. Note that in this case, there is only a single value in the enumeration, and this value is the INSTANCE.

Related