Applied Design Patterns with Java

Creational :: Factory Method (107) {C ch 4}


Collaborations

Consequences

Factory Method eliminates the need to bind application-specific classes into code. The code only deals with the Product interface; therefore it can work with any user-defined ConcreteProduct classes.

A potential disadvantage of
Factory Method is that clients might have to subclass the Creator class to create a particular ConcreteProduct object. Subclassing is fine when the client has to subclass the Creator class, otherwise the client now must deal with another point of evolution.

Here are two more consequences of the
Factory Method pattern:

  1. Provides hooks for subclasses. Creating objects inside a class with a Factory Method is always more flexible than creating an object directly. Factory Method gives subclasses a hook for providing an extended version of an object. In the Document example, the Document class could define a Factory Method called CreateFileDialog that creates a default file dialog object for opening an existing document. A Document subclass can define an application-specific file dialog by overriding this Factory Method. Factory Method is not abstract but provides a reasonable default implementation.
  2. Connects parallel class hierarchies. In the examples considered so far, the Factory Method is only called by Creators. Clients can find factory methods useful, especially in the case of parallel class hierarchies. Parallel class hierarchies result when a class delegates some of its responsibilities to a separate class. With these constraints, it's better to use a separate Manipulator object that implements the interaction and keeps track of any manipulation-specific state that's needed. Different figures will use different Manipulator subclasses to handle particular interactions. The resulting Manipulator class hierarchy parallels (at least partially) the Figure class hierarchy:


Catalog Creational Prev Next