Java Reference
In-Depth Information
Factory Method (Chapter 16)
SOLUTION 16.1
Many answers are possible, but toString() is probably the most commonly used method
that creates a new object. For example, the following code creates a new String object:
String s = new java.util.Date().toString();
The creation of strings often happens behind the scenes. Consider:
System.out.print(new Date());
This method creates a String object from the Date object, ultimately by calling
the toString() method of class Date . It is interesting to walk through this in debugger, to
see the details of what happens within a common print() method.
Another method that creates a new object is clone() . You may discover other methods that
are "factories" for creating objects without necessarily exemplifying the F ACTORY M ETHOD
pattern.
SOLUTION 16.2
The intent of the F ACTORY M ETHOD pattern is to let an object provider determine which class
to instantiate when creating an object. By comparison, clients of BorderFactory know
exactly what object types they're getting. The pattern at play in BorderFactory is
F LYWEIGHT , in that BorderFactory uses sharing to efficiently support large numbers of
borders. The BorderFactory class isolates clients from managing the reuse of objects,
whereas F ACTORY M ETHOD isolates clients from knowing which class to instantiate.
SOLUTION 16.3
A good answer, perhaps, is that you do not need to know what class of object
an iterator() method returns. What is important is that you know the interface that the
iterator supports, which lets you walk through the elements of a collection. However, if you
must know the class, you can print out its name, with a line like:
System.out.println(i.getClass().getName());
In the version of Java used in this topic, this statement prints out:
java.util.AbstractList$Itr
The class Itr is an inner class of AbstractList . You should probably never see this class
in your work with Java.
Search WWH ::




Custom Search