Java Reference
In-Depth Information
CHALLENGE 16.2
Explain how the intent of F ACTORY M ETHOD is different from the intent of
the BorderFactory class.
You might feel that a method like Arrays.asList() , which instantiates an object and has
an interface return type, is an example of F ACTORY M ETHOD . After all, such methods do
isolate a client from knowing which class to instantiate. But the spirit of F ACTORY M ETHOD
is that the object creator makes a choice about which of several possible classes to instantiate
for the client. The Arrays.asList() method instantiates the same type of object for every
client, so this method does not fulfill the intent of F ACTORY M ETHOD .
Usually, you will find that several classes in a hierarchy implement the F ACTORY M ETHOD
operation. Then the decision of which class to instantiate depends on the class of the object
that receives the call to create. In other words, F ACTORY M ETHOD lets subclasses decide
which class to instantiate.
Many classes, including those in hierarchies, implement the toString() method. But the
toString() method always returns a String object. The classes that implement
toString() do not determine which class to instantiate, so this method is not an example of
F ACTORY M ETHOD .
A Classic Example of Factory Method: Iterators
The I TERATOR pattern (see Chapter 28, Iterator) provides a way to access the elements of
collection sequentially. But iterator() methods themselves are usually good examples of
the F ACTORY M ETHOD pattern. An iterator() method isolates its caller from knowing
which class to instantiate. The Java JDK version 1.2 release introduced the Collection
interface, which includes the iterator() operation. All collections implement this
operation.
An iterator() method creates an object that returns a sequence of the elements of a
collection. For example, the following code creates and prints out the elements of a list:
package com.oozinoz.applications;
import java.util.*;
public class ShowIterator
{
public static void main(String[] args)
{
List list =
Arrays.asList(
new String[] {
"fountain", "rocket", "sparkler" });
Iterator i = list.iterator();
while (i.hasNext())
{
System.out.println(i.next());
}
}
}
Search WWH ::




Custom Search