Java Reference
In-Depth Information
Implementation
The Singleton class diagram is shown in Figure 1.6 .
Figure 1.6. Singleton class diagram
To implement the Singleton pattern, you need:
Singleton - Provides a private constructor, maintains a private static reference to the single instance of this
class, and provides a static accessor method to return a reference to the single instance.
The rest of the implementation of the Singleton class is normal. The static accessor method can make decisions
about what kind of an instance to create, based on system properties or parameters passed into the accessor
method (see the Pattern Variants section for this pattern).
Benefits and Drawbacks
Benefits and drawbacks include the following:
The Singleton is the only class that can create an instance of itself. You can't create one without using the static
method provided.
You don't need to pass the reference to all objects needing this Singleton.
However, the Singleton pattern can present threading problems, depending upon the implementation. You must
take care regarding control of the singleton initialization in a multithreaded application. Without the proper
control, your application will get into “thread wars.”
Pattern Variants
Pattern variants include the following:
One of the Singleton's often-overlooked options is having more than one instance inside the class. The benefit is
that the rest of the application can remain the same, while those that are aware of these multiple instances can use
other methods to get other instances.
The Singleton's accessor method can be the entry point to a whole set of instances, all of a different subtype. The
accessor method can determine at runtime what specific subtype instance to return. This might seem odd, but it's
very useful when you're using dynamic class loading. The system using the Singleton can remain unchanged,
while the specific implementation of the Singleton can be different.
Related Patterns
Related patterns include the following:
Abstract Factory ( page 6)
Builder (page 13)
Prototype ( page 28)
 
 
Search WWH ::




Custom Search