650 likes | 819 Views
Unit 21 Factory Method. Summary prepared by Kirk Scott. Design Patterns in Java Chapter 16 Factory Method. Summary prepared by Kirk Scott. Ordinary construction relies on the existence of constructors in a base class The Factory Method design pattern also relies on these ordinary constructors
E N D
Unit 21Factory Method Summary prepared by Kirk Scott
Design Patterns in JavaChapter 16Factory Method Summary prepared by Kirk Scott
Ordinary construction relies on the existence of constructors in a base class • The Factory Method design pattern also relies on these ordinary constructors • The idea is that client code may not know or care specifically which kind of object it is working with • What it cares about is that the object implements a desired interface
Suppose the client works with several different base classes • Each of these base classes, in turn, may rely on/create instances of different underlying classes, which the client needs an instance of • Each of the base classes will implement a factory method which returns an object of a given interface • The underlying classes all implement that interface • The actual type of the underlying object returned to the client will depend on the logic of the particular base class that implements the factory method
Book definition: • The intent of the 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 • Iterators provide a way to access the elements of a collection sequentially • There is a Collection interface • Every class that implements the Collection interface has to implement the method iterator() • The iterator() method returns an instance of an iterator
In this example, the Collection interface is not “the” interface of the Factory Method design pattern • The Collection interface is simply the mechanism that makes sure that every implementing class has an iterator() method • The iterator() method is the factory method
The point is this: • You can call iterator() on any collection class • The iterator() method returns something that is typed Iterator • However, Iterator is not a class • Iterator is an interface
The class of the object returned by a call to the iterator() method differs according to which kind of object it was called on • The iterator() method could be called on an ArrayList and the type of the actual object returned would be an iterator for an ArrayList • The iterator() method could be called on a HashMap and the type of the actual object returned would be an interator for a HashMap
The client code doesn’t care what the actual type of object is • Formally, it only cares that it be typed Iterator • Functionally, this means that the client code can call on any iterator any of the methods defined in the Iterator interface • The client code does not need to be able to call any class specific methods, if they even exist
The code on the following overhead illustrates the creation and use of an iterator for a collection of type List • The List itself is constructed by hard coding a simple array of strings and passing it in to the List object
import java.util.*; • public class ShowIterator • { • public static void main(String[] args) • { • List list = Arrays.asList( • new String[] { "fountain", "rocket", "sparkler" }); • Iteratoriter = list.iterator(); • while (iter.hasNext()) • System.out.println(iter.next()); • // Uncomment the next line • // to see the iterator's actual class: • // System.out.println(iter.getClass().getName()); • } • }
Challenge 16.1 • What is the actual class of the Iterator object in this code?
Solution 16.1 • 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(iter.getClass().getName());
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. • [End of Solution 16.1.]
Recognizing Factory Method • There are many methods floating around object-oriented code which return references to newly created objects of one class or another • Just because a method returns such a reference doesn’t mean that it implements the Factory Method design pattern.
Challenge 16.2 • Name two commonly used methods in the Java class libraries that return a new object. • [And don’t implement the Factory Method design pattern.]
Solution 16.2 • There are many possible answers, 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 Date().toString(); • The creation of strings often happens behind the scenes.
Consider: • System.out.println(new Date()); • This code creates a String object from the Date object, ultimately by calling the toString() method of the Date object. • Another frequently used method that creates a new object is clone(), a method that usually returns a copy of the receiving object. • [End of Solution 16.2.]
The point of the answers to the previous challenge is this: • toString() and clone() don’t exhibit the Factory Method design pattern • They don’t protect the client (the calling code) from knowing what kind of object is being constructed and returned • There is no set of classes under the covers that implement a common interface which is the type returned by the calls to the methods
Challenge 16.3 • The class javax.swing.BorderFactory sounds like it ought to be an example of the Factory Method pattern. • Explain how the intent of the Factory Method pattern is different from the intent of the BorderFactory class.
Comment mode on: • This challenge basically boils down to a red herring • It’s like asking whether the so-called Adapter classes in Java implement the Adapter design pattern • The answer is no, it’s just the use of the same word to mean a different thing
Solution 16.3 • The intent of the Factory Method 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 Flyweight, in that BorderFactory uses sharing to efficiently support large numbers of borders.
The BorderFactory class isolates clients from managing the reuse of objects, whereas Factory Method isolates clients from knowing which class to instantiate. • [End of Solution 16.3.]
Taking Control of Which Class to Instantiate • The book now moves on from examples like iterator(), which already exist in Java • It paints a scenario where client code needs to obtain a credit limit for a customer • If a credit agency is online, then the credit limit is generated with an instance of a class named CreditCheckOnline
If the credit agency is offline, then the credit check is generated with an instance of a class named CreditCheckOffline • The method that the client code is going to call is creditLimit() • The client code doesn’t care exactly what kind of object is returned • The UML diagram on the following overhead illustrates the situation so far
The key point of this example is that we’re one step lower down in the implementation details than we were in the iterator example • In the iterator example, the iterator() method was simply a given for each class that implemented the Collection interface • If you called iterator() on an object, it returned an instance of the right kind of iterator
In this example, the CreditCheckOnline and the CreditCheckOffline classes are roughly analogous to the different types of iterator • When this example is fully worked out, there will be another class which contains the factory method • When the factory method is called on an instance of that class, it will determine whether to construct an instance of CreditCheckOnline or CreditCheckOffline
The book outlines these elements of an application of the Factory Method design pattern to this situation: • 1. Make a CreditCheck interface that includes a creditLimit() method • 2. Have the classes CreditCheckOnline and CreditCheckOffline implement this interface
3. Make a CreditCheckFactory class with a createCreditCheck() method that returns an object of type CreditCheck • When you first look at these classes, it may be tempting to think that the creditLimit() method in the two base classes is analogous to the iterator() method in the foregoing example • In other words, you might think that the creditLimit() method is the factory method
However, this is not the case • The creditLimit() method returns a reference, to an instance of Dollars • This is practically the same as returning a simple type • More importantly, both implementations of creditLimit() return the same type of thing
There is no choice there of what to create • The creditLimit() method is analogous to the hasNext() method in the Iterator interface • hasNext() can be called on any object that implements the Iterator interface
In the iterator example the overarching question is, what kind of iterator is it, an ArrayListiterator, a HashMapiterator? • In this example the question is, what kind of credit limit is it, an online or offline one? • It is the method createCreditCheck() that returns a reference to one kind of object or another • It is this method that is the factory method
Challenge 16.4 • Draw a class diagram that establishes a way for this new scheme to create a credit-checking object while retaining control of which class to instantiate.
Solution 16.4 • Figure B.18 shows that the two credit check classes implement the CreditCheck interface. • The factory class provides a method that returns a CreditCheck object. • The client that calls createCreditCheck() does not know the precise class of the object it receives.
Solution 16.4, continued • The createCreditCheck() method is a static method, so clients need not instantiate the CreditCheckFactory class in order to get a CreditCheck object. • You can make this class abstract or give it a private constructor if you want to actively prevent other developers from instantiating it. • [End of Solution 16.4.]
Once again, this is the basic idea of the example: • Client code doesn’t know whether credit checking is available online or offline • It simply wants a credit check generated • It does this by calling createCreditCheck() • The logic of the code for that method determines which kind of actual credit check object is returned • However, whatever is returned, it will implement the CreditCheck interface
Challenge 16.5 • Assume that the CreditCheckFactory class has an isAgencyUp() method that tells whether the credit agency is available, and write the code for createCreditCheck().
Solution 16.5 • If you take a leap of faith that the static method isAgencyUp() accurately reflects reality, the code for createCreditCheck() is simple: • public static CreditCheckcreateCreditCheck() • { • if(isAgencyUp()) • return new CreditCheckOnline(); • return new CreditCheckOffline(); • }
Factory Method in Parallel Hierarchies • Given a hierarchy of classes, you may decide to move a subset of behavior out of the classes and implement it in separate classes • The result is a parallel hierarchy of classes • The Factory Method design pattern can arise in such a situation
The book illustrates this with machines and machine managers in a fireworks factory • The example is not exactly the same, but you may notice similarities with the material presented in the chapter on the Bridge pattern • The UML diagram on the next overhead gives the starting point for the example • There are various concrete types of machine that extend the abstract Machine class
The scenario is that you would like to have a getAvailable() method for machines for planning purposes • However, the logic for implementing getAvailable() is relatively complex • A parallel hierarchy arises when you decide to factor out the management functionality
More background information includes the following: • getAvailable() is supposed to forecast when a machine will finish its current work and become available • Most machine types will have different logic, requiring different kinds of planner (classes) • Mixers and fusers are simple and quick enough that the are essentially always available and they can share the same kind of planner (class)
Challenge 16.6 • Fill in the diagram of a Machine/MachinePlanner parallel hierarchy in Figure 16.3.
Solution 16.6 • Figure B.19 shows a reasonable diagram for the Machine/MachinePlanner parallel hierarchy.