What is Singleton Design Pattern?
A class must ensure that only one single instance should be created and that single object can be used by all other classes.Advantages:
Save memory because an object is not created each request. Only one instance is using every time.Usage:
This pattern is mostly using in multi-threaded and database applications. It is using in logging, caching, thread pools, configuration settings, etc.
How to create a singleton design pattern?
To create a singleton class, we need to have static member of class, private constructor and factory method.
- Static member: It gets memory only once because of static, it contains the instance of the singleton class.
- Private constructor: It will prevent to instantiate the singleton class from outside the class.
- Static factory method: This provides access to the singleton object and returns the instance to the caller.
Method 1:
Create the instance of the class at the time of declaring the static member, so the instance of the class is created at the time of class loading.
Method 2:
Create the instance of the class in a synchronized method or synchronized block, so the instance of the class is created when required
No comments:
Post a Comment