In the question What is an efficient way to implement a singleton pattern in Java? the answer with the most upvotes says, to use a Enum for implementing a singleton.
That is fine and I understand the arguments, respectively the language advantages.
I have, however, a set of classes which I define singleton but which need to extend other classes, this is not possible with the enum approach, since enums cannot subclass.
Joshua Bloch says in his slides:
- But one thing is missing—you can’t extend an enum type
- In most cases, you shouldn’t
- One compelling use case—operation codes
In most cases you shouldn’t: could someone elaborate on that? I have implemented several servlets and they extend HttpServlet, why shouldn’t these be singletons? I only want one instance of them in my application.
A Singleton class can extend other classes; actually by default in Java it would anyway extend Object. However what Josh is referring to is that you shouldn’t extend a Singleton class because once you extend it, there is more than 1 instance present.
Answering the comment:
Actually the best way to implement the Singleton is:
From Effective Java
Here Elvis can extend any other class.