Design Pattern Download: The Singleton Pattern
The singleton pattern is a Creational Pattern used in software engineering to ensure that there is only one instance of an object at a time. This can be useful if the object requires a substantial amount of overhead to setup or if there is some shared resource or state throughout the application (i.e. global variables) or if the application is multi-threaded and we need to ensure that the state of the system is thread safe.
Example
Imagine we have a program that generates multiple threads all of which communicate to a DataBase. We could have each thread create their own DBAccessor instance and use it for their own process.
Using that method…
- We need to create multiple DBAccessors which means we have to preform whatever set up the DBAccessor needs N times.
- We create an issue of out of sync data (i.e. two threads try to write to the DB using two instances at the same time) which can lead to overriding and or inconsistent data.
The Singleton Pattern fixes this…
- With one Singular instance across the entire application, we will now only need to set up the DBAccessor 1 time.
- We can make the DBAccessor methods synchronized so that only one thread can access it at a time which will remove the issue of out of sync data.
When to use the Singleton Pattern?
- When an object requires a lot of compute power to setup.
- When we have a multi-threaded with a shared resource.
What is the Singleton Pattern composed of?
- The Singleton (a Class with a private constructor and a method to get the instance)
Implementation
The Singleton 🗄️(Class)
The Singleton class will have a private instance variable of the class itself and use the private constructor to create an instance of itself. To get said instance, we create a static function getInstance which will return the object we set up. The user can then call the instance method callDDB using the DBAccessor instance returned.