There Can Be Only One: The Singleton Design Pattern
an example of the Singleton Pattern and why it is used
When to use the Singleton Pattern?
The Singleton Pattern is used when you only want one instance of an object at a time.
An example when this pattern is useful is for an access point to a database 💾. In an app, it is beneficial to have one entry point to the database as opposed to multiple entry points (like what would happen with a regular class with a constructor).
In the image above, we have three users asking for a box 📦, our box service gives them pointers to the same instance instead of creating new ones for each of them. This is useful if creating a “box” is an expensive or long task ⏱️, with singleton, we only need to create one.
Case Study
We will create a small app where we have a DBAccessor class which we only want one to exist at a time. We will have 2 clients request to use the accessor and confirm that they are both using the same one.
The Singleton
Here is an example of a Singleton class, we get rid of the default constructor by explicitly declaring a private constructor so it cannot be called 🚫 outside the class.
If a client wants to get the instance of DBAccessor, they will have to use the getInstance() method.
Here we create two dbAccessors which actually point to the same object.
Query number 1
Query number 2
When we query the two “different” objects, we are actually querying the same one so it increments to 1 and then 2. If we got different instances, we would have seen…
Query number 1
Query number 1
The Singleton Pattern is one of the simplest and easiest understood design patterns, there is a clear understanding of how to implement it and when and why you would want to use a singleton over a regular Object with a public constructor.