Singleton Design Pattern: (Factory Design Pattern here)
What is Singleton Design Pattern?
Singleton Design pattern makes sure that there is only one instance of class is created and restricts developers to create multiple instances of same class.
Why do we need Singleton Design Pattern?
Singleton Design pattern is used when we have to limit the system for only one instance. This is used when we have to share some resources and to use specific resource the program should cross this point.
Steps for Creating Singleton Class:
- The instance should be private static final to make it singleton
- Constructor should be private (to restrict the instantiation of object directly)
- public static method for callers to get reference
Example:
public class SingletonSolution { private static final SingletonSolution singletonSolution = new SingletonSolution(); // private static final instance private static SingletonSolution getSingletonSolution(){ // callers to get this instance return singletonSolution; } private SingletonSolution(){ // Private Constructor } }
Difference Between Static and Singleton Class:
Static | Singleton |
---|---|
Greater Performance (since static is used at compile time) | Less performance when compared to static |
Static class is eagerly loaded | Singleton class can be lazy loaded |
Disadvantages of Singleton Design Pattern:
- Singleton classes cannot be sub-classed.
- Singleton can hide dependencies
Factory Design Pattern here
[…] Design Pattern: (Singleton Design Pattern here) What is Factory Design Pattern? We need to define an interface or abstract class to create an […]