Singleton design pattern — get the gist in 2 min
Singleton ensures there is only one instance created for the class, and this instance is shared when requested by the client class.
Singleton pattern ensure a class has only one instance and provide a global point of access to it — GoF design patterns
It’s a type of creational design pattern.
Singleton pattern is a convention for ensuring only one instance of a class is created.
Structure and the simple example :
The structure is very simple where the Singleton class has to have a private constructor so that outside classes will not have the chance to create an instance of the class, and it provides a method getInstance() whose responsibility is to return a reusable singleton instance of a class.
There are ways you can still able to create an instance of a class even if it has a private constructor but those are not standard ways to create an instance, and all of those can be restricted by using tricks while developing a singleton class.
There are three ways we can implement a singleton pattern :
1) Non-thread safe singleton pattern
2) Threadsafe singleton pattern
3) eager instantiation singleton pattern .
read here more details on the code and check here github code.
In Spring framework , when a bean is defined the default scope for that bean is singleton.
In the below syntax a bean “product” is created as a singleton in the application context it has been created.
It’s also interesting to know in springs default scope is singleton and default loading mechanism is eager instantiation of a bean.
<bean name="product" class="com.foo.Product"/>
The real fun is in the details, if you wish to know and understand different styles of singleton pattern and java code examples, pros-cons, please consider visiting my detailed article at [singleton-pattern-java-explained-4-min-read]
Thanks for reading. Love IT, Live IT, Enjoy IT.
On the journey to understand the core essence of design patterns.
Every week I publish a small 2 min post and a long 5–10 min post along with a code example, please consider following if you wish to get notified!