Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.

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

T O K ILL A S INGLETON F ACTORY M ETHOD P ATTERN Josh Mason 6/18/09.
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
Factory Pattern Building Complex Objects. New is an implementation  Calling “new” is certainly coding to an implementation  In fact, it’s always related.
CS 210 Introduction to Design Patterns September 19 th, 2006.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Template Method By: Mahmoodreza Jahanseir Amirkabir University of Technology Computer Engineering Department Fall 2010.
Prototype Pattern Intent:
DESIGN PATTERNS Redesigning Applications And
March Ron McFadyen1 Singleton pattern Singleton is designed to restrict instantiation of a class to one (or a few) objects. Useful when exactly.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
+ Informatics 122 Software Design II Lecture 8 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Design Patterns.
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.
Creational Patterns (1) CS350, SE310, Fall, 2010.
02 - Creational Design Patterns Moshe Fresko Bar-Ilan University תשס"ח 2008.
Software Components Creational Patterns.
Abstract Factory Abstract Factory using Factory Method.
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.
Design Patterns Façade, Singleton, and Factory Methods Team Good Vibrations (1)
Decorator Explained. Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for.
Creational Patterns CSE Creational Patterns Class creational pattern ◦ uses inheritance to vary the class that is instantiated Object creational.
Programming in Java CSCI-2220 Object Oriented Programming.
CS 210 Review Session October 5 th, Head First Design Patterns Chapter 4 Factory Pattern.
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.
Abstract Factory and Factory Method CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
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.
Prototype pattern Participants Prototype (Graphic) – declared an interface for cloning itself ConcretePrototype (EditBox, Slider) – implements an operation.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CS 590L – Distributed Component Architecture 02/20/2003Uttara Paingankar1 Design Patterns: Factory Method The factory method defines an interface for creating.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
FACTORY METHOD. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
Billy Bennett June 22,  Intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Design Patterns Introduction
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
The Factory Pattern Sanjay Yadav (ISE ).
Advanced Object-oriented Design Patterns Creational Design Patterns.
CSC 480 Software Engineering Design With Patterns.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
SE 461 Software Patterns. ABSTRACT FACTORY PATTERN.
SE 461 Software Patterns. FACTORY METHOD PATTERN.
Command Pattern. Intent encapsulate a request as an object  can parameterize clients with different requests, queue or log requests, support undoable.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
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 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Factory Method Pattern. Admin SCPI Patner Day Feb. 21 Lunch count Presentation (4-8 min.) Practice on Feb. 16. Morning availablity on Feb21 Brief overview.
Design Patterns: MORE Examples
Factory Method Pattern
Low Budget Productions, LLC
Factory Patterns 1.
Software Design and Architecture
Software Design and Architecture
Factory Method Pattern
CSE 432 Presentation GoF: Factory Method PH: “To Kill a Singleton”
Lesson 5: More on Creational Patterns
Creational Patterns.
CSC 480 Software Engineering
Software Design Lecture : 28.
Presentation transcript:

Factory Method Explained

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.  a.k.a. Virtual Constructor  The main intent of the virtual constructor idiom in C++ is to create a copy of an object or a new object without knowing its concrete type and this is exactly what the Factory Method does  Can a constructor be virtual? 2

Motivation  Frameworks use abstract classes to define and maintain relationships between objects  A framework is often responsible for creating these objects as well  They must instantiate classes but only know about abstract classes - which they cannot instantiate  Factory method encapsulates knowledge of which subclass to create - moves this knowledge out of the framework 3

Motivation (Cont’d)  Consider a framework for presenting multiple documents to the user  Key abstraction in this framework are Application and Document classes  Both classes are abstract and realized in subclasses  Application class is responsible for managing and creating the Documents as and when required. 4

Motivation (Cont’d)  The particular Document subclass to instantiate is application specific, and  The Application class can’t predict the subclass of Document to instantiate. As it only knows when a new document should be created. NOT  What kind of a Document to create.  This creates a dilemma… 5

Motivation (Cont’d)  Factory method solves this problem. It encapsulates the knowledge of which Document to create and moves this knowledge out of the framework. factory method 6

Motivation (Cont’d)  Application subclasses redefine an abstract CreateDocument operation to return Document subclasses  Once an Application subclass is instantiated, it can then instantiate application specific Documents  We call CreateDocument a factory method as it’s responsible for manufacturing a object. 7

Applicability  Use the Factory Method pattern when  A class can’t anticipate the class of objects it must create  A class wants it’s subclasses to specify the objects it creates  Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. 8

Structure 9

Participants  Product (Document)  defines the interface of objects the factory method creates  Concrete Product (MyDocument)  Implements the product interface  Creator (Application)  declares the factory method which return a Product type.  May also define a default implementation of the factory method that returns a default ConcreteProduct object  May call the factory method to create a Product object.  Concrete Creator (MyApplication)  Overrides the factory method to return Concrete Product 10

Collaborations  Creator relies on it’s subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct(Subclasses of Product) 11

Consequences  Factory methods eliminate the need to bind application specific classes into your code  The code only deals with the Product interface; therefore it can work with any user defined ConcreteProduct classes.  A potential disadvantage of using Factory pattern is that client also has to subclass the Creator class in order to create a particular ConcreteProduct object. 12

Consequences (Cont’d)  Provides hooks for subclasses  Creating objects inside a class with a factory method is always more flexible than creating an object directly  Factory method gives subclasses a hook for providing an extended version of an object  Example: the Document class could define a factory method called CreateFileDialog for opening an existing document. 13

Consequences (Cont’d)  Connects Parallel Class Hierarchies  Parallel Class hierarchies result when a class delegates some of it’s responsibilities to a separate class  Clients can use factory methods to connect between parallel class hierarchies 14

Consequences (Cont’d)  The figure class provides a CreateManipulator factory method that lets clients create a Figure’s corresponding Manipulator  Figure subclasses override this method to return an instance of the required manipulator subclass  Alternatively the Figure class may implement CreateManipulator to return a default manipulator. The figure subclasses may inherit the default.  The figure classes that do so need no corresponding Manipulator subclasses. Hence partially parallel class hierarchies  This is how the factory method defines connection between these class hierarchies 15

Implementation Styles  Two Major Varieties  The case when the Creator class is an abstract class and does not provide an implementation of factory method  The case when the Creator class is a concrete class and has a default implementation of the factory method  The first case requires subclasses to define an implementation as there is no reasonable default  In the second case the subclasses or concrete Creator uses factory method primarily for flexibility. 16

Implementation Styles (Cont’d)  Parameterized factory methods  create multiple kinds of products  the factory method takes a parameter that identifies the kind of object to create  the object share the Product interface  Naming conventions  The name of the Factory method in code should clearly mark its purpose. 17

Implementation  So the situation is that you have a set of related concrete classes and there may be some conditions to call any one of them 18

Implementation (Cont’d)  When we see code like this we know that when it comes to changes and extensions, we will have to re-open this code and examine what needs to be added or deleted.  Often this type of code ends up in several parts of an application making maintenance and updates more difficult and error prone.  By coding to an interface we know we can insulate ourselves with lot of changes occurring down the road  However if you have concrete classes then you might end up in trouble if more concrete classes are added  In other words code would not be closed for modification  So what’s the solution? 19

Implementation (Cont’d) 20  Remember the design principle “Identify the aspects that vary and separate them from what stays the same”  We will now see an example implementation of Pizza shop to illustrate the application of this design principle  We will have a function of OrderPizza() to determine one type of Pizza and run different processes for making a pizza.

Implementation (Cont’d) 21 public class Pizza { Pizza pizza; //Declarations public Pizza() { } //Constructor of Pizza //Declarations of Pizza Functions public virtual void Prepare() {} public virtual void Bake() { } public virtual void Cut() { } public virtual void Box() { } //Method of Ordering a Pizza public void OrderPizza() { pizza = new Pizza(); pizza.Prepare(); pizza.Bake(); pizza.Cut(); pizza.Box(); } //Return only one type of Pizza

Implementation (Cont’d) 22  The concrete classes of Pizza like cheese pizza and pepperoni pizza public class CheesePizza : Pizza { public CheesePizza() { Console.WriteLine("Constructing CHEESE PIZZA"); } public override void Prepare() { Console.WriteLine("Preparing CHEESE PIZZA"); } public override void Bake() { Console.WriteLine("Baking CHEESE PIZZA"); } public override void Cut() { Console.WriteLine("Cutting CHEESE PIZZA"); } public override void Box() { Console.WriteLine("Boxing CHEESE PIZZA"); } }

Implementation (Cont’d) 23 public class PepperoniPizza : Pizza { public PepperoniPizza() { Console.WriteLine("Constructing Pepperoni Pizza"); } public override void Prepare() { Console.WriteLine("Preparing Pepperoni Pizza"); } public override void Bake() { Console.WriteLine("Baking Pepperoni Pizza"); } public override void Cut() { Console.WriteLine("Cutting Pepperoni Pizza"); } public override void Box() { Console.WriteLine("Boxing Pepperoni Pizza"); } }

Implementation (Cont’d) 24  Now we will add code that determines different types of pizza and then goes about making it. The order pizza function will change public void OrderPizza(String type){ if (type.Equals("Cheese")){ pizza = new CheesePizza(); //Calling object of Subclass for Cheese Pizza } else if (type.Equals("Pepperoni")) { pizza = new PepperoniPizza();//Calling object of Subclass for Pepperoni Pizza } pizza.Prepare(); pizza.Bake(); pizza.Cut(); pizza.Box(); }

Implementation (Cont’d) 25  We have now passed the type of pizza (string type) to OrderPizza function  Based on the type of pizza we instantiate the correct concrete class and assign it to the pizza instance variable.  Note that each pizza here would have to implement the pizza interface.  So each pizza type knows how to prepare itself.  But the pressure in on to add or subtract pizza types

Implementation (Cont’d) 26 public void OrderPizza(String type){ if (type.Equals("Cheese")){ pizza = new CheesePizza(); } else if (type.Equals("Pepperoni")){ pizza = new PepperoniPizza(); } // “here we can add more pizza types” pizza.Prepare(); pizza.Bake(); pizza.Cut(); pizza.Box(); } This part of code is changing This part of code is supposed to remain unchanged

Implementation (Cont’d) 27  Clearly we can now make out what’s variable in our code and we need to separate it  What we can do is that place the object creation code into another object (class) whose sole purpose is to create different types of pizza  This object can be called a SimplePizzaFactory  Once we have a factory the OrderPizza() becomes a client of that factory. Anytime it needs a pizza it asks the factory to make one  OrderPizza will get a correct pizza and would call prepare(),bake(),cut() and box()

Implementation (Cont’d) 28  Here is the new class SimplePizzaFactory public class SimplePizzaFactory { public SimplePizzaFactory() { } public Pizza CreatePizza(String type)//This method would be used by all to create new objects { Pizza pizza = null; if (type.Equals("Cheese")) { pizza = new CheesePizza(); //Calling object of Subclass for Cheese Pizza } else if (type.Equals("Pepperoni")) { pizza = new PepperoniPizza();//Calling object of Subclass for Pepperoni Pizza } return pizza; }

Implementation (Cont’d) 29  The orderpizza method also be moved out of the Pizza class and would be changed as under public class PizzaStore { SimplePizzaFactory factory = new SimplePizzaFactory(); //Creates the factory public PizzaStore() { } public void OrderPizza(String type) { Pizza pizza; pizza = factory.CreatePizza(type); //Get the correct pizza from Factory pizza.Prepare(); pizza.Bake(); pizza.Cut(); pizza.Box(); }//Method of Ordering a Pizza }

Implementation (Cont’d) 30

Implementation (Cont’d) 31  Now the Pizza class would be changed as under public abstract class Pizza //Superclass Pizza { public Pizza() { } //Contructor of Pizza //Declarations of Pizza Funtions public virtual void Prepare() { } public virtual void Bake() { } public virtual void Cut() { } public virtual void Box() { } }

Implementation (Cont’d) 32  The calling program for our code class Program { static void Main(string[] args) { PizzaStore pizzastore = new PizzaStore();// The client just knows the pizza store pizzastore.OrderPizza("Pepperoni"); Console.ReadLine(); }

Quiz # 1 33  Elements of a Design Pattern with an example  Describe Scope Based Design Patterns Classification?