25/04/2024
Many devs think singleton pattern means :- static keyword. Singleton is a pattern while static is a keyword.
To implement a proper singleton pattern we need to atleast have 6 things at place.
Below are numbered bullet points and check those numbered bullet points with image attached.
1. Whole part relationship: - The first thing needed in singleton is a root class through which all shared objects should be exposed. This root class instance should be created inside the class and it should be static.
2. Thread safety: - Whenever we are loading the singleton object use the βlockβ keyword to make sure only one thread manipulates at a time or else we will have thread unsafe code.
3. Private constructor: - Make sure the root class can not be instantiated from outside.
4. Ensure root object is single instance: - use the double null check and make sure that only one instance is created and also lock is not executed unnecessarily.
5.Lazy loading implementation: - We would like to load the objects when demanded then loading it unnecessarily.
6.Performance for threading: - Let us see this point 6 how many devs can explain, how does it increase performance ?. Please comment in the comment section.
Happy learning.