The singleton pattern was part of the original Design Patterns collection. It makes sure that a class, which we call a singleton class, has only one instance. In other words, only one object of that class may ever be created during the program's life. Such a class must also provide global access to this instance.
Let me give a real-life example to clarify this definition. You probably live in a country that allows one, and only one, president (or monarch, head of state, and so on.) to exist at the same time. So, that person is a singleton.
You will notice that the pattern tells us nothing about how that one singleton instance should be destroyed. It also doesn't specify when the singleton instance should be created.
Whenever you need to create a singleton, you should first answer the following questions:
- Does the singleton have to be initialized on demand...