The Singleton pattern has two primary criteria for applicability:
- The class should have exactly one instance which should be accessible from a method in the class.
- The class can be subclassed, and clients can use the subclass as an instance of the superclass without having to change anycode.
The first criterion more or less defines the nature of the Singleton pattern.
The second criterion considers issues of reuse. In many cases there is more than one way to solve the immediate problem.
You choose your pattern more for how easily it can be modified within your system rather than for what it does.
The Singleton pattern is grouped with the other Creational patterns
, although it is to some extent a non-creational
There are any number of cases in programming where you need to make sure that there can be one and only one instance of a class.
For example, your system can have only one window manager or print spooler, or a single point of access to a database engine.
The easiest way to make a class that can have only one instance is to embed a static variable
inside the class that we set on the first instance and check for each time we enter the constructor.
A static variable is one for which there is only one instance, no matter how many instances there are of the class.
static boolean instance_flag = false;
The problem is how to find out whether creating an instance was successful or not, since constructors do not return values.
One way would be to call a method that checks for the success of creation, and which simply returns some value derived from the static variable.
This is inelegant and prone to error. However, because there is nothing to keep you from creating many instances of such non-functional classes and forgetting to check for this error condition.