For me, a singleton makes sense wherever you want to present something unique of its kind.
As an example, if we want to model the Sun , it cannot be a normal class, because there is only one Sun However, it makes sense to inherit it from the Star class. In this case, I would choose a static instance with a static getter.
To clarify, here is what I am saying:
public class Star { private final String name; private final double density, massInKg; public Star(String name, double density, double massInKg) {
Sun can use all Star methods and define new ones. This would not be possible with an enumeration (class extension, I mean).
If you don’t need to model such inheritance relationships, as you said, enum becomes more appropriate, or at least simpler and more understandable. For example, if an application has one ApplicationContext for the JVM, it makes sense to have it as a singleton, and usually it does not need to inherit anything or be extensible. Then I would use enum .
Please note that in some languages, such as Scala, there is a special keyword for singletons ( object ), which not only makes it easy to define single numbers, but also completely replaces the concept of a static method or field.
source share