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 the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.