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.
I would argue the most common way to implement a singleton is to use an enum with one instance. That might be a "better" way but definitely not the most common way. In all the projects I have worked on, Singletons are implemented as I have shown above.
Yes. A singleton class has a private constructor which is not accessible to any other class inside the same package or outside. Hence it cannot be sub classed from any other class. purpose but it can be done.
By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.
There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw a run-time exception in the constructor if the instance already exists. In this, we can not able to create a second instance.
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
// Singleton with static factory
public class Elvis {
private static final Elvis INSTANCE = new Elvis();
private Elvis() { ... }
public static Elvis getInstance() { return INSTANCE; }
public void leaveTheBuilding() { ... }
}
Here Elvis can extend any other class.
You shouldn't care about the actual instance(s) of your servlets - lifecycle management is handled by the servlet container according to the Servlet specification contract to which you have agreed. If it makes sense to implement parts of you server-side functionality as a singleton, then go ahead and do that any way you like and use it from your servlet.
Josh is referring to extending the enum type, not to having the singleton type extend something else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With