Tip #16: Understand the Singleton Pattern
Sorry, this tip is longer than usual, but it’s a good discussion!
My opinion about Design Patterns has changed over the years: I believe you need to know about them, but if you can finish your project without implementing any, it's probably better.
Hey Bruno, it’s not Friday! (In case you’re wondering, I usually post these controversy tips on Fridays!)"
I like what the Java Champion Venkat Subramaniam told once in a presentation: "As more powerful a language is, less we talk about Design Patterns as these naturally became features of the language".
But, you probably will need it ( interviews, other languages) so here is a definition:
The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it. It’s classified as a creational pattern because it lets you create an object while hiding the creation logic.
If you search for Singleton implementations, you always find some code like this:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor to prevent instantiation
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
It’s in books, tutorials, and if you implemented a Singleton, you probably used it.
In Java, the best way according to Joschua Bloch in Effective Java is to use an enum:
public enum Singleton {
INSTANCE;
}
"This approach is similar to the public field approach, but it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks."
Bonus
If you are a Spring developer, by default, your beans are all singletons, so make sure you understand the pros and cons. IMPORTANT: When you create a bean in Spring, by default, it will be a singleton. But it’s a singleton per Spring IoC container, so two different containers will have different instances of the same bean. The other difference from the Singleton Pattern is that Spring beans are created by the Spring IoC container, not by the class itself.
I’d love to hear your thoughts—have you implemented a Singleton using an enum? Share your use cases or challenges with me.
Happy coding!