Singleton
When you only need one copy of an object, such as a manager for a type or resource access point, it can reveal new requirements. Two requirements typically come out of a demand for uniqueness.
You may want to guarantee there’s never more than one for safety or security reasons. Or it may be because it makes no sense to have more than one. Uniqueness guarantees are easier to make if you use strong countermeasures.
If there’s only one, then there’s the question of how to access the only copy. How do you ensure no other part of the code accidentally creates an additional instance because it could not find the proper one?
The GoF solution is to make construction the job of the class, not an object. The suggestion is that other local instances can be created when the type itself doesn’t claim responsibility for maintaining uniqueness, even with a single global pointer to store the instance. Notice that in some languages, class objects (as opposed to object instances) are Singletons, but not all.
There are three problems which keep occurring with
- Non-deterministic construction.
- Lack of destruction.
- Global shared state.
Non-deterministic construction has a two-fold effect. Something is going to be
the first thing to fetch the instance. That will cause a spike in the
processing at that point, but undeservedly so. My background is computer games
and finding that a
The second timing-related issue is one of non-deterministic creation order. If
a system constructs on first use and use is based on something
non-deterministic, your program will create
Many things are non-deterministic in reality. If the object is only accessed based on data loaded and the application is multi-threaded or the system is referenced based on user input or even their reaction time, then consider the system to be created randomly.
Dynamic or lazy creation has bitten me several times, and again, it’s easy to
fix by explicitly calling the getInstance
of each
I prefer explicitly creating each object during the early phase and placing it in a globally accessible location.
The second main problem—the lack of destruction—presents additional issues.
Usually,
Destruction is also my preference. I like to delete all
The third and last main problem with
A stateful singleton seems as dangerous as any other global variable. But
without state, the
“I am unique. No others like me. I’m a self-made object. You can find me by name alone.”