Design Patterns Java™ Workbook

(Michael S) #1

Chapter 16. Factory Method......................................................................................................................


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 FACTORY METHOD 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 FACTORY METHOD 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 FACTORY METHOD pattern. The FACTORY METHOD pattern requires that an operation
that creates an object also isolates its client from knowing which class to instantiate. In
FACTORY 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 FACTORY METHOD 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 FACTORY METHOD 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 FACTORY METHOD pattern.


Table 16.1. Characteristics of Factory Method
CREATES AN OBJECT
RETURNS ABSTRACT CLASS OR
INTERFACE
IMPLEMENTED BY SEVERAL
CLASSES

METHOD^ INSTANCE OF FMETHOD ACTORY^


BorderFactory.
createEtchedBorder()


x

Arrays.asList() x x


toString() x x^


iterator() x x x x

Free download pdf