Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.

Similar presentations


Presentation on theme: "The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1."— Presentation transcript:

1 The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1

2 Motivating Example A list (a.k.a. sequence or vector) is an ordered collection of objects. Lists are common in many applications. There are several ways to implement a list, with varying degrees of runtime performance in different usage scenarios. Two common approaches for implementing lists are as follows: –linked-based data structure –array-based data structure The Java library provides a List interface with several different implementations including –LinkedList –ArrayList ©SoftMoore ConsultingSlide 2

3 Motivating Example (continued) Suppose that a context uses a list and needs an iterator for that list. Different implementations of the List interface will need different implementations of an iterator. How can we create an iterator that is appropriate for a specific programming context? What if we had to call “ new ” to create an iterator for each different implementation? public void processNames(List names) { Iterator iter; if (names instanceof LinkedList) iter = new ???(); else if (names instanceof (ArrayList) iter = new ???();... } ©SoftMoore ConsultingSlide 3 Warning: Bad code!

4 Motivating Example (continued) This code is awkward and not maintainable. –If we had to call new to create an iterator, we would need to repeat this code in all similar usage scenarios. –What about other list implementations in Java? Should we add additional “ else if ” branches to the code? –What if the next version of Java adds a new implementations for the List interface? Using the Factory Method pattern, the responsibility for creating an appropriate iterator is moved from the context that needs the iterator to the concrete List subclass that knows which iterator implementation to create. ©SoftMoore ConsultingSlide 4

5 Factory Method Pattern Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Also Known As: Virtual Constructor Applicability: Use the Factory Method pattern when –a class can’t anticipate the class of objects it must create. –a class wants its subclasses to specify the objects it creates. –classes delegate responsibility to one of several helper classes, and you want to localize the knowledge about which helper subclass is the delegate. Slide 5©SoftMoore Consulting

6 Factory Method Pattern (continued) ©SoftMoore ConsultingSlide 6 Product ConcreteProduct... Product p = factoryMethod()... Creator factoryMethod() anOperation() ConcreteCreator factoryMethod() return new ConcreteProduct() creates/returns a new Product Structure Discussion of this pattern in terms of lists and iterators.

7 Factory Method Pattern (continued) Participants Product –defines the interface class of objects that the factory method creates. ConcreteProduct –Implements the Product interface. Creator –declares the factory method, which returns an object of type Product. –may define a default implementation of the factory method. –may call the factory method to create a Product object. ConcreteCreator –overrides the factory method to return an instance of a ConcreteProduct Slide 7©SoftMoore Consulting

8 Factory Method Pattern (continued) Collaborations: Creator relies on its subclass to define the factory method so that it returns an instance of the appropriate ConcreteProduct. Implementation –Creator class can be abstract or concrete. A concrete Creator class could provide a default implementation for the factory method. –Generics (a.k.a. templates in C++) can often be used to avoid subclassing the creator. (Product class still needs to be subclassed). –The factory method can be parameterized, allowing it to create multiple kinds of products. ©SoftMoore ConsultingSlide 8

9 Example: Parameterized Factory Method public class Creator { public Product create(ProductID id) { if (id == 1) return new Product1(); if (id == 2) return new Product2();... return null; } ©SoftMoore ConsultingSlide 9

10 MazeGame Example public class MazeGame { public Maze createMaze() {... } // factory methods public Maze makeMaze() {... } public Room makeRoom() {... } public Wall makeWall() {... } public Door makeDoor() {... } } ©SoftMoore ConsultingSlide 10

11 MazeGame Example (continued) Different games can subclass MazeGame to specialize parts of the maze. MazeGame subclasses can redefine some or all of the factory methods to specify variations in products. public class BombedMazeGame extends MazeGame {... // overrides factory methods // makeWall() and makeRoom() } ©SoftMoore ConsultingSlide 11

12 Factory Method Pattern in Java (Revisiting the Motivating Example) In Java, the Collection interface declares a factory method iterator() that returns an Iterator for the collection. List is a subinterface of Collection. Concrete implementations of List (e.g., LinkedList ) override the iterator() method to return an iterator appropriate for the implementation. The user does not need to know the name of the class that implements the iterator. public void processNames(List names) { Iterator iter = names.iterator();... } ©SoftMoore ConsultingSlide 12 calls a Factory Method

13 Comments on the Factory Method Pattern The Factory Method pattern uses inheritance and polymorphic methods to delegate responsibility for object creation to subclasses. The “classic” Factory Method pattern describes a class with a creational method that –is virtual (can be overridden) –returns a concrete instance of an interface or abstract type A related concept is the static factory method, a public static method that returns an instance of its containing class. –Example: The getInstance() method of the Singleton pattern is essentially a static factory method for the single instance of the class. ©SoftMoore ConsultingSlide 13

14 Factory Method Pattern in Java In class Calendar public abstract class Calendar { /** * Gets a calendar using the default time zone * and locale. */ public static Calendar getInstance() {... }... } ©SoftMoore ConsultingSlide 14 Method getInstance() in class Calendar is an example of a static factory method in Java.

15 Another Example: JDBC Connection Factory public final class ConnectionFactory { private static ConnectionFactory instance = null; private String url; private String user; private String pw; protected ConnectionFactory(String url, String user, String pw) throws SQLException { this.url = url; this.user = user; this.pw = pw; } ©SoftMoore ConsultingSlide 15 Singleton (continued on next page)

16 Another Example: JDBC Connection Factory (continued) public static synchronized ConnectionFactory getInstance() { if (instance == null) { try { Properties props = CommonProperties.getInstance(); String url = props.getProperty("dbUrl"); String user = props.getProperty("dbUser"); String pw = props.getProperty("dbPassword"); Class.forName(props.getProperty("driverName")); instance = new ConnectionFactory(url, user, pw); } catch (Exception ex) {... } } return instance; } ©SoftMoore ConsultingSlide 16 (continued on next page) Static FactoryMethod

17 Another Example: JDBC Connection Factory (continued) public synchronized Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } ©SoftMoore ConsultingSlide 17 FactoryMethod

18 Using the JDBC Connection Factory ConnectionFactory factory = ConnectionFactory.getInstance(); Connection conn = factory.getConnection(); ©SoftMoore ConsultingSlide 18 Note that client code client is isolated from details about user name, pw, etc., even about which database is being used for the connection (except that some knowledge of database specific SQL differences might be needed).

19 Related Concept: Factory Class A factory class is a class created solely for the purpose of creating objects. Example 1: Class MazeGame mentioned earlier uses virtual methods. Example 1: Class javax.swing.BorderFactory uses static factory methods. public class BorderFactory { public static Border createBevelBorder(int type) {... } public static Border createLineBorder(Color color) {... }... } ©SoftMoore ConsultingSlide 19

20 Other Examples of Factory Method in Java Class java.util.ResourceBundle public static final ResourceBundle getBundle(String baseName) –returns a resource bundle using the specified base name and the default locale Class java.text.NumberFormat public static final NumberFormat getInstance() –returns a general-purpose number format for the default locale ©SoftMoore ConsultingSlide 20 Factory Method is often recognizable by creational methods that return an implementation of an abstract/interface type.

21 Methods that Create New Objects A method that creates a new object is not necessarily a Factory Method. A Factory Method not only creates a new object, it also isolates a client from having to know which class to instantiate. With Factory Method, there are usually several classes that implement a method with the same signature but return different implementations of the same interface or abstract type. Example – the toString() method in Java is not usually considered to be a Factory Method. ©SoftMoore ConsultingSlide 21

22 Advantages of Factory Methods (from Effective Java) Unlike constructors, factory methods have names. –can be more descriptive –can have multiple methods with the same parameters and different names Unlike constructors, factory methods are not required to create a new object each time that they are invoked. –immutable classes can use preconstructed instances; e.g., Boolean.valueOf(). Unlike constructors, factory methods can return an object of any subtype of their return type. –e.g., the iterator() factory method in Java collection classes. ©SoftMoore ConsultingSlide 22

23 Related Patterns Classes that support iteration often use a factory method to create the iterator. Abstract Factory is often implemented with Factory Methods. Factory Methods are usually called within Template Methods. ©SoftMoore ConsultingSlide 23

24 References Factory method pattern (Wikipedia) http://en.wikipedia.org/wiki/Factory_method_pattern Factory Method Pattern (Object-Oriented Design) http://www.oodesign.com/factory-method-pattern.html Factory Method Design Pattern (SourceMaking) http://sourcemaking.com/design_patterns/factory_method Effective Java (Second Edition) by Joshua Bloch Item 1: Consider static factory methods instead of constructors ©SoftMoore ConsultingSlide 24


Download ppt "The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1."

Similar presentations


Ads by Google