Singleton Design Pattern
Singleton pattern:
- Singleton pattern belongs to the creational pattern.
- It allows one instantiation or object for JVM
Rules for singleton pattern:
- The constructor should be private.
private Singleton()
{
}
- We can not create an object outside of the class.
Singleton singleton=new Singleton(); //Not possible to create an object using new keyword because the constructor is private
Advantages of singleton pattern:
- It controls multiple object creations by allowing only one-time creation.
Use cases of singleton pattern:
- Logging is a popular use of Singletons. It provides one single access point to an applications log file.
Issues with singleton pattern:
- If two threads call the getInstance() method at the same time, you can end up with two singletons.
- If we make getInstance() method synchronized then it solves the issue, but we need to sacrifice performance because synchronized getInstance() is a costly operation.
The secret of getting ahead is getting started.
Hello rakeshbecse!
Congratulations! This post has been randomly Resteemed! For a chance to get more of your content resteemed join the Steem Engine Team