Java Reference
In-Depth Information
Code 13.1
continued
The Singleton pattern
{
return
instance;
}
private
Parser()
{
...
}
}
In this pattern:
■
The constructor is private so that instances can be created only by the class itself. This has
to be in a static part of the class (initializations of static fields or static methods), because no
instance will otherwise exist.
■
A private static field is defined and initialized with the (sole) instance of the parser.
■
A static
getInstance
method is defined, which provides access to the single instance.
Clients of the Singleton can now use that static method to gain access to the parser object:
Parser parser = Parser.getInstance();
13.7.4
Factory method
The
Factory method
pattern provides an interface for creating objects but lets subclasses decide
which specific class of object is created. Typically, the client expects a superclass or an inter-
face of the actual object's dynamic type, and the factory method provides specializations.
Iterators of collections are an example of this technique. If we have a variable of type
Collection
, we can ask it for an
Iterator
object (using the
iterator
method) and then work
with that iterator (Code 13.2). The
iterator
method in this example is the Factory method.
Code 13.2
A use of a factory
method
public
void
process(Collection<Type> coll)
{
Iterator<Type> it = coll.iterator();
...
}
From the client's point of view (in the code shown in Code 13.2), we are dealing with objects of type
Collection
and
Iterator
. In reality, the (dynamic) type of the collection may be
ArrayList
,
in which case the
iterator
method returns an object of type
ArrayListIterator
. Or it may
be a
HashSet
, and
iterator
returns a
HashSetIterator
. The Factory method is specialized in
subclasses to return specialized instances to the “official” return type.
We can make good use of this pattern in our
foxes-and-rabbits
simulation, to decouple the
Simulator
class from the specific animal classes. (Remember: In our version,
Simulator
Search WWH ::
Custom Search