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.