The enum singleton is only a singleton if you define one enum value. If you define more than one value, then you have as many instances as you have values. In your case there would be three instances of the enum class. By definition, you no longer have a singleton at that point.
Enums were not explicitly meant to allow the creation of singletons. Someone just noticed that the way enums work would make them a better and perhaps cleaner way to essentially define a Singleton.
But if there are three instances getting created, if there are three constants, than that's not the singleton. There must be the way to restrict enums to create a single instance irrespective of number of ENUM Constants.
Otherwise I can definately create the singleton object using class by creating just a single object of that class in the same way I create the single ENUM constant, without writing any additional code of restricting that class?
Again, enums were not introduced into the language so that we could create singletons. It just so happens that the way enums work, it makes it a convenient mechanism for creating a singleton.
Your assertion that there should be a way to limit the number of enum values is like saying that because you can turn a car into a bed, there should be a way to register a bed so you can drive it on the highway.
Enums are primarily meant to define a finite set of constant values so that there is stricter type checking. Just because a single enum value can be used to represent a singleton doesn't mean the language should provide a means to limit the number of values defined. That is solely a design decision that is in the purview of the designer/programmer. If you don't want more than one value in your enum type, then just don't define more than one. It's that simple.
You can find out more about the real motivation for introducing enums to Java by searching for "java typesafe enum pattern" -- As you'll see, the motivation is primarily about type safety and not about creating Singleton objects.
Enum with 3 constants would be 3 singletons ?
Convenient for descriptive data which should have only one instantiation throughout a program.
I personally use it for application menu description.
I can then have several engines to parse the menu structures and render it in different ways
I use it as well for database table columns description,
then have an SQL engine code generator which can parse those enums and create various SQL queries
Laurent de Laprade wrote:Enum with 3 constants would be 3 singletons ? . . .
I think that a class with exactly three instances is a variation of a Singleton. But, as stated previously, a singleton is not necessarily a good thing. Many people think it is a bad thing. I don't think the enum pattern was designed for what you are doing, even though you seem to have got it to work. You ould probably do the same with multiple text files containing the parts of the SQL code to interpose into the constant parts.