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

Slides:



Advertisements
Similar presentations
Creational Design Patterns. Creational DP: Abstracts the instantiation process Helps make a system independent of how objects are created, composed, represented.
Advertisements

Creational Patterns (2) CS350/SE310 Fall, Lower the Cost of Maintenance Economic Goal Coupling-Cohesion, Open-Close, Information-Hiding, Dependency.
Creational Patterns, Abstract Factory, Builder Billy Bennett June 11, 2009.
T O K ILL A S INGLETON F ACTORY M ETHOD P ATTERN Josh Mason 6/18/09.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Prototype Pattern Intent:
Design Patterns Examples in C++ Moshe Fresko Bar-Ilan University Object Oriented Programming
Inheritance and Polymorphism CS351 – Programming Paradigms.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Abstract Factory Pattern.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. The Factory Method Design Pattern (1) –A creational design.
Design Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns II.
Design patterns. What is a design pattern? Christopher Alexander: «The pattern describes a problem which again and again occurs in the work, as well as.
CSC 142 O 1 CSC 142 Java More About Inheritance & Interfaces [Reading: chapter 13]
Creational Patterns (1) CS350, SE310, Fall, 2010.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
02 - Creational Design Patterns Moshe Fresko Bar-Ilan University תשס"ח 2008.
Software Components Creational Patterns.
12/6/20041 The Factory Method Pattern Presenters 王世賀 F 陳祐毓 F 張峻銘 F 吳佩達 F 林俊成 F 鄭榮智 F 許書豪 F
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Creational Patterns CSE Creational Patterns Class creational pattern ◦ uses inheritance to vary the class that is instantiated Object creational.
Factory Method Chris Colasuonno Also known as “Virtual Constructor”
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method Pattern.
The Factory Method Design Pattern Motivation: Class / Type separation – Abstract class serves as type definition and concrete class provides implementation.
CDP-1 9. Creational Pattern. CDP-2 Creational Patterns Abstracts instantiation process Makes system independent of how its objects are –created –composed.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Creational Pattern: Factory Method At times, a framework is needed to standardize the behavior of objects that are used in a range of applications, while.
CS 590L – Distributed Component Architecture 02/20/2003Uttara Paingankar1 Design Patterns: Factory Method The factory method defines an interface for creating.
FACTORY METHOD. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
Design Patterns Introduction
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns I.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Factory Pattern Sanjay Yadav (ISE ).
Advanced Object-oriented Design Patterns Creational Design Patterns.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Singleton Pattern (Creational)
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
 Creational design patterns abstract the instantiation process.  make a system independent of how its objects are created, composed, and represented.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Overview of Creational Patterns ©SoftMoore ConsultingSlide 1.
The Abstract Factory Pattern (Creational) ©SoftMoore ConsultingSlide 1.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Class Relationships Lecture Oo08 Polymorphism. References n Booch, et al, The Unified Modeling Language User Guide, Chapt 10 p.125 n Fowler & Scott, UML.
SOFTWARE DESIGN Design Patterns 1 6/14/2016Computer Science Department, TUC-N.
07 - Creational PatternsCSC4071 Creational Patterns Patterns used to abstract the process of instantiating objects. –class-scoped patterns uses inheritance.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Factory Method. Intent/Purpose Factory Method is used to deal with a problem of creating objects without specifying the EXACT class of object that we.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Factory Method Pattern
Low Budget Productions, LLC
Factory Patterns 1.
Inheritance and Polymorphism
Software Design and Architecture
Creational Design Patterns
Factory Method Pattern
Software Engineering Lecture 7 - Design Patterns
Java Programming Language
CSE 432 Presentation GoF: Factory Method PH: “To Kill a Singleton”
More About Inheritance & Interfaces
Chapter 14 Abstract Classes and Interfaces
CIS 199 Final Review.
Creational Patterns.
Presentation transcript:

The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1

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

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!

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

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

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.

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

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

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

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

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

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

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

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.

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)

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

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

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).

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

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.

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

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

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

References Factory method pattern (Wikipedia) Factory Method Pattern (Object-Oriented Design) Factory Method Design Pattern (SourceMaking) Effective Java (Second Edition) by Joshua Bloch Item 1: Consider static factory methods instead of constructors ©SoftMoore ConsultingSlide 24