Java Reference
In-Depth Information
Chapter 8. Singleton
Objects can usually act responsibly just by performing their own work on their own attributes,
without incurring obligations beyond self-consistency. Some objects, though, take on further
responsibilities, such as modeling real-world entities, coordinating work, or modeling the
overall state of a system. When a particular object in a system bears a responsibility on which
other objects rely, you need a way of finding the responsible object. For example, you might
need to find an object that represents a particular machine or a customer object that can
construct itself from data in a database or an object that initiates system memory recovery.
When you need to find a responsible object, the object that you need will, in some cases, be
the only instance of its class. For example, at Oozinoz, there is at present only one factory and
only one Factory object. In this case, you need S INGLETON . The intent of the S INGLETON
pattern is to ensure that a class has only one instance and to provide a global point of access to
it.
Singleton Mechanics
The mechanics of S INGLETON are more memorable than its intent. It is easier to explain how
to ensure that a class has only one instance than it is to say why you might want this
restriction. You might categorize S INGLETON as a "creational" pattern, as Design Patterns
(Gamma et al. 1995) does. You should, of course, think of patterns in whatever way helps you
remember, recognize, and apply them. But the intent of the S INGLETON pattern implies that a
specific object bears a responsibility on which other objects rely.
You have some options about how you create an object that takes on a unique role. But
regardless of how you create a singleton, you have to ensure that other developers don't create
new instances of the class you intend to limit.
CHALLENGE 8.1
How can you prevent other developers from constructing new instances of your
class?
When you design a singleton class, you need to decide when to instantiate the single object
that will represent the class. One choice is to create this instance as a static field in the class.
For example, the Runtime class in java.lang includes the line:
private static Runtime currentRuntime = new Runtime();
This class makes its unique instance available through its public, static getRuntime()
method.
Rather than creating a singleton instance ahead of time, you might wait until the instance is
first needed, or lazy-initialize it. For example, a Factory class might make its single
instance available with:
Search WWH ::




Custom Search