16 Factory Method

WHEN YOU DEVELOP a class, you usually provide class constructors to let clients of your class instantiate it. Sometimes, though, a client that needs an object does not or should not know which of several possible classes to instantiate.

The intent of FACTORY METHOD is to let a class developer define the interface for creating an object while retaining control of which class to instantiate.

A Classic Example: Iterators

The ITERATOR pattern provides a way to access the elements of a collection sequentially. (See Chapter 28, ITERATOR.) But the way iterators are created often uses a FACTORY METHOD. Java JDK version 1.2 introduced a Collection interface that includes an iterator() method; all collections implement ...

Get Design Patterns in Java™, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.