SINGLETON – Hey, I privately control my own creation to ensure all of you get my single unique copy. No piracy allowed!
It’s a creational design pattern that ensures that there is only a single instance of the class available for everyone to use.
This is useful in managing shared data and configurations in the application.
Importantly, we must remember that the uniqueness of such instance is confined to its runtime instance. For example, in java each JVM instance can have its separate singleton object. Hence, in a distributed environment we may need additional implementation to ensure the contents of singleton instances are the same and synchronized.
How does the pattern work?
A singleton basically has two important things manage.
1. Limit Number of Instances to One :
- A Private Constructor in Java helps us achieve this by restricting any class other than the Singleton class to create an instance.
2. Load & Manage the Shared Data :
We can choose to load the data at the time of class loading but, it might impact the loading time. Hence, in case of time consuming data load process, we may choose to use lazy loading. Thus, we can categories data loading in singletons into the following two categories :
- Eager Loading Data
- Easy and useful for light data loading.
- Lazy Loading Data
- This is the recommended approach for heavy and time consuming data loading process.
- Since we might get overlapping data loading requests, these methods need to be made thread safe.
So, let us look at an example code to understand it better.
Summary of the benefits
- Its very useful in adding new features to objects with complex structures.
- Its keeps the processing logic clean by separating the traversal logic .