112 | Chapter 3: Singleton Pattern
You may be wondering how this was possible, because the second instance did not
drop into the part of the constructor that actually created the Singleton instance:
Singleton._instance=new Singleton(new PrivateClass( ));
However, it did not have to because the line,
return Singleton._instance
contains the Singleton instance that had already been created, and simply returned
that instance to the reference name.
While you can guarantee that only one instance of the Singleton class will exist at
any one time, more than a single reference to that instance can exist at the same time
as well. For a shared property used with either increments or decrements, this can be
a very handy way of making sure that only a single source is used by all of the refer-
ences. If, for instance, you’re making a game to save miners trapped in a mineshaft,
you need to keep track of the amount of oxygen available for the miners. So if you
create anOxygenclass as a Singleton, all of the miner characters can create a refer-
ence to it, and each one can access a method in the single instance that decrements
the amount of air. Because the amount of air has to be the same for all, the Singleton
becomes a handy tool for keeping track of the many references to the single instance
of the class.
When to Use the Singleton Pattern
As noted at the beginning of this chapter, the Singleton design pattern is best
employed when you need one and only one instance of a class in an application. A
couple of examples were discussed, but the use of the Singleton is so ubiquitous in
object-oriented programming that it’s sort of like asking when to use a variable.
Moreover, developers often combine the Singleton design pattern with other pat-
terns. Where the developer needs a single, global entry point and a single instance,
you’ll often find a Singleton class. Likewise, multiple Singleton classes can be used in
conjunction when you have several different objects where only a single instance of
each object should be instantiated at any one time.
Figure 3-5. Two instance labels and one instance