Applied Design Patterns with Java
Creational :: Singleton (127) {C ch 6}
Implementation
Here are implementation issues to consider when using the
Singleton pattern:
- Ensuring
a unique instance. The Singleton pattern makes
the sole instance a normal instance of a class, but that class is written so that only one instance can ever be
created. A common way to do this is to hide the operation that creates the instance behind a class operation (that
is, either a static member function or a static class method) that guarantees only one instance is created. This
operation has access to the variable that holds the unique instance, and it ensures the variable is initialized
with the unique instance before returning its value. This approach ensures that a Singleton is created and
initialized before its first use. An added (albeit small) liability of the global/static object approach is that
it forces all singletons to be created whether they are used or not. Using a static member function avoids all
of these problems.
- Subclassing
the Singleton class. The main issue is not
so much defining the subclass but installing its unique instance so that clients will be able to use it. In essence,
the variable that refers to the singleton instance must get initialized with an instance of the subclass. The simplest
technique is to determine which singleton you want to use in the Singleton's Instance operation.
- Subclassing.
Another way to choose the subclass of Singleton
is to take the implementation of Instance out of the parent class and put it in the subclass. That lets a C++ programmer
decide the class of Singleton at link-time (e.g., by linking in an object file containing a different
implementation) but keeps it hidden from the clients of the Singleton. The link approach fixes the choice of Singleton
class at link-time, which makes it hard to choose the Singleton class at run-time. Using conditional statements to determine the
subclass is more flexible, but it hard-wires the set of possible Singleton classes. Neither approach is flexible enough in all cases.
- A
more flexible approach uses a registry of Singletons. Instead
of having Instance define the set of possible Singleton classes, the Singleton classes can register their Singleton instance by name
in a well-known registry. No longer is the Singleton class responsible for creating the Singleton. Instead, its
primary responsibility is to make the Singleton object of choice accessible in the system. The static object approach
still has a potential drawback—namely that instances of all possible Singleton subclasses must be created, or else they won't get registered.
Related Patterns
Many patterns can be implemented using the Singleton pattern.
See Abstract Factory (87), Builder
(97), and Prototype (117).
Catalog Creational Prev Next