Factory Method Joey Richey Kevin Gorski
Definition Allows a class developer define the interface for creating an object while retaining control of which class to instantiate. Metsker -Design Patterns Java Workbook
Main Points Creates a new object Returns a type that is an abstract class or interface Is implemented by several classes
Example (Iterators) Iterator() method isolates its caller from knowing which class to instantiate Creates an object that returns a sequence of the elements in a collection
Challenege 16.3 What class is the Iterator object in this code: List list = Arrays.asList(new String[] {“fountain”, “rocket”, “sparkler” }); Iterator i = list.iterator(); Java.util.AbstractList$Itr
File Operations (GoF) Have an application that shows multiple documents to the user The document and application classes are abstract Application class can't predicite which document class it going to be used
Credit Check Example Oozinoz will start letting customers buy fireworks on credit Your task is to develop the credit authorization system The credit agency can be in two states: online and offline Initial design: two separate classes CreditCheckOnline and CreditCheckOffline
Problem: now the user of the classes needs to know which class to instantiate
Solution: Commit to the interface for creating an object but keep control of which class to instantiate (use the Factory pattern) Challenge 16.4 – – Draw a class diagram that establishes a way to create a credit-checking object while retaining control of which class to instantiate.
Solution 16.4
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 public static CreditCheck createCreditCheck() { if ( isAgencyUp()) { return new CreditCheckOnline(); } else { return new CreditCheckOffline(); }
Factory Method in Parallel Hierarchies A parallel hierarchy is a pair of class hierarchies in which each class in one hierarchy has a corresponding class in the other hierarchy.
Figure 16.2
getAvailable() method forecasts when a machine will complete its current processing to be available for more work This method may require a lot of support Create a separate MachinePlanner hierarchy You need a separate planner class for most machine types, but mixers and fusers are always available for additional work (use BasicPlanner class)
Figure 16.6
Summary The intent of the Factory Method pattern is to define the interface for creating a new object so that a service provider decides which class to instantiate instead of clients. Common in application code and parallel class hierarchy.