Be mindful when creating objects; sometimes, we only need one of a specific type. Creating a single object that lives throughout the lifetime of a program is a form of Singleton design pattern. As simple as the concept may be, we should take extra care when implementing it, mainly when many codes use that object concurrently.
You, A Person, As A Singleton Object
Let us apply the concept of the Singleton design pattern in a practical scenario. Suppose you are the lone cash register person (a singleton object) at a busy supermarket. Also, imagine there is no queue for customers, and everyone checks out simultaneously (concurrently). As a result, you, as the lone cashier person, will not be able to process the transactions accurately and correctly. Amid the hustle and bustle, some items might slip through deliberately. Worse, people run off with unpaid goods!
What is the solution to this problem with this case of the Singleton design pattern? The supermarket could force customers to queue up and check out one at a time. Also, we could scale that by hiring additional people and putting up more cash registers.
Imagine that scenario at the code level.
The Singleton Pattern Off The Gang of Four
What does the Gang of Four tell about this Singleton design pattern?
Ensure a class only has one instance, and provide a global point of access to it.
The intent of the pattern is to provide a single instance of a class. Also, any code in the codebase has access to it.
Other Design Patterns
The Singleton design pattern is only one of the creational design patterns we can use to create maintainable software applications. Check out the other design patterns on Design Patterns Are The Ultimate Toolkit For Programmers.