Download presentation
Presentation is loading. Please wait.
1
Factory Method Joey Richey Kevin Gorski
2
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
3
Main Points Creates a new object Returns a type that is an abstract class or interface Is implemented by several classes
5
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
6
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
7
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
9
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
10
Problem: now the user of the classes needs to know which class to instantiate
11
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.
12
Solution 16.4
13
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().
14
Solution 16.5 public static CreditCheck createCreditCheck() { if ( isAgencyUp()) { return new CreditCheckOnline(); } else { return new CreditCheckOffline(); }
15
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.
16
Figure 16.2
17
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)
18
Figure 16.6
19
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.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.