Java Reference
In-Depth Information
Chapter 16. Factory Method
As a class developer, you will ordinarily provide class constructors to let users of your class
instantiate it. Sometimes, however, a client that needs an object does not or should not know
which of several possible classes to instantiate. The F
ACTORY
M
ETHOD
pattern lets a class
developer define the interface for creating an object while retaining control of which class to
instantiate.
Recognizing Factory Method
You might think any method that creates and returns a new object is a "factory" method. In
object-oriented programming, however, methods that return new objects are common, and not
every such method is an instance of the F
ACTORY
M
ETHOD
pattern.
CHALLENGE 16.1
Name two commonly used Java methods that return a new object.
The fact that a method creates a new object does not in itself mean that it is an example of
the F
ACTORY
M
ETHOD
pattern. The F
ACTORY
M
ETHOD
pattern requires that an operation
that creates an object also isolates its client from knowing which class to instantiate. In
F
ACTORY
METHOD,
you will find several classes that implement the same operation, returning
the same, abstract type but internally instantiating different classes that implement the type.
To summarize, the signs that F
ACTORY
M
ETHOD
is at work are that an operation:
•
Creates a new object
•
Returns a type that is an abstract class or an interface
•
Is implemented by several classes
Table 16.1 shows a few methods from the Java class libraries; these methods have all or some
of the characteristics of the F
ACTORY
M
ETHOD
pattern. For example, the
BorderFactory
class has a variety of methods that create and return new objects. The class is a factory but is
not an example of the F
ACTORY
M
ETHOD
pattern.
Table 16.1. Characteristics of Factory Method
CREATES AN OBJECT
RETURNS ABSTRACT CLASS OR
INTERFACE
IMPLEMENTED BY SEVERAL
CLASSES
INSTANCE OF F
ACTORY
M
ETHOD
METHOD
BorderFactory.
createEtchedBorder()
x
Arrays.asList()
x
x
toString()
x
x
iterator()
x
x
x
x