Factory Patterns. DCS – SWC 2 Being less concrete One important OO principle is: ”Program to an interface, not an implementation” Interfaces reduces the.

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

CS 350 – Software Design The Bridge Pattern – Chapter 10 Most powerful pattern so far. Gang of Four Definition: Decouple an abstraction from its implementation.
Creational Patterns, Abstract Factory, Builder Billy Bennett June 11, 2009.
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Generics. DCS – SWC 2 Generics In many situations, we want a certain functionality to work for a variety of types Typical example: we want to be able.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Prototype Pattern Creational Pattern Specify the kinds of objects to create using a prototypical instance, and create new objects by copy this prototype.
THE OBJECT-ORIENTED DESIGN WORKFLOW Interfaces & Subsystems.
Prototype Pattern Intent:
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Pattern Abstract Factory
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Design Patterns.
CSC 142 O 1 CSC 142 Java More About Inheritance & Interfaces [Reading: chapter 13]
ECE 452 / CS 446 / SE464 Design Patterns: Part 2 - Answers A Tutorial By Peter Kim Partially based on the tutorial by Michał Antkiewicz.
SE2811 Week 7, Class 1 Composite Pattern Applications Conceptual form Class structure Coding Example Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark.
Abstract Factory Design Pattern making abstract things.
Tech Talk Go4 Factory Patterns Presented By: Matt Wilson.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Software Components Creational Patterns.
1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming.
CS 350 – Software Design The Strategy Pattern – Chapter 9 Changes to software, like other things in life, often focus on the immediate concerns and ignore.
1 Web Based Programming Section 8 James King 12 August 2003.
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
Factory Patterns. RHS – SOC 2 Being less concrete One important OO principle is: ”Program to an interface, not an implementation” Interfaces reduces the.
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2.
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method Pattern.
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.
SWE 316: Software Design and Architecture – Dr. Khalid Aljasser Objectives Lecture 13 Creational Design Pattern SWE 316: Software Design and Architecture.
XML. DCS – SWC 2 Data vs. Information We often use the terms data and information interchangeably More precisely, data is some ”value” of a certain type,
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Religious Studies 313 – Advanced Programming Topics.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Interfaces and Polymorphism CS 162 (Summer 2009).
Advanced Object-oriented Design Patterns Creational Design Patterns.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
 Creational design patterns abstract the instantiation process.  make a system independent of how its objects are created, composed, and represented.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
(c) University of Washington05-1 CSC 143 Java Abstract Classes and Frameworks Reading: Ch. 11.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
Command. RHS – SWC 2 Executing a command Executing a command appears simple at first, but many details to consider: –Who creates a command? –Who invokes.
CS 350 – Software Design The Decorator Pattern – Chapter 17 In this chapter we expand our e-commerce case study and learn how to use the Decorator Pattern.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
Abstract Factory Pattern Jiaxin Wang CSPP Winter 2010.
Abstract Factory pattern Intent Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Design Patterns: MORE Examples
Abstract Factory Pattern
Factory Patterns 1.
Abstract Factory Pattern
Intent (Thanks to Jim Fawcett for the slides)
Abstract Factory Pattern
Polymorphism and access control
Generics.
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
More About Inheritance & Interfaces
Creational Patterns.
Designing For Testability
Presentation transcript:

Factory Patterns

DCS – SWC 2 Being less concrete One important OO principle is: ”Program to an interface, not an implementation” Interfaces reduces the coupling between code and concrete types Code does not need to know the concrete type of an object

DCS – SWC 3 Being less concrete Animal sleep() makeSound() lookForFood() Dog sleep() makeSound() lookForFood() Horse sleep() makeSound() lookForFood()

DCS – SWC 4 Being less concrete Animal oneAnimal = new Horse(); … oneAnimal.sleep(); oneAnimal.makeSound(); oneAnimal.lookForFood(): …

DCS – SWC 5 Being less concrete Animal oneAnimal = new Dog(); … oneAnimal.sleep(); oneAnimal.makeSound(); oneAnimal.lookForFood(): …

DCS – SWC 6 Being less concrete This is fine, but we still need to be concrete when creating an object Also, we might need to choose – at run-time – between various concrete types

DCS – SWC 7 Being less concrete Animal oneAnimal; … if (needToRide) oneAnimal = new Horse(); else if (mustBeMammal) oneAnimal = new Dog(); else oneAnimal = new Parrot(); … oneAnimal.sleep(); oneAnimal.makeSound(); oneAnimal.lookForFood(): …

DCS – SWC 8 Being less concrete Is anything wrong with this…? What if we need to add some new concrete types? In that case, we will need to change the code in order to include the new types ”Closed for modification, open for extension…”

DCS – SWC 9 Being less concrete We want to isolate the references to concrete types to another class One class produces concrete objects, using their concrete types Another class processes the objects, knowing only the interface The processing class can then be closed for modification

DCS – SWC 10 Being less concrete A class which produces objects is usually called a Factory Class A factory class usually has a single method: create(…) The create method often – but not always – takes a parameter, defining what concrete object to create

DCS – SWC 11 Being less concrete Animal sleep() makeSound() lookForFood() Dog sleep() makeSound() lookForFood() Horse sleep() makeSound() lookForFood() AnimalFactory Animal create(String info)

DCS – SWC 12 Being less concrete public class AnimalFactory { public Animal create(String info) { if (info.equals(”Dog”)) return new Dog(); else if (info.equals(”Horse”)) return new Horse(); else if (info.equals(”Parrot”)) return new Parrot(); else return null; }

DCS – SWC 13 Being less concrete AnimalFactory fac; … Animal oneAnimal = fac.create(”Dog”); … oneAnimal.sleep(); oneAnimal.makeSound(); oneAnimal.lookForFood(): …

DCS – SWC 14 Being less concrete Have I achieved something, or am I just moving code around…? With this setup, we can now parameterise the processing code further This removes the last references to concrete types

DCS – SWC 15 Being less concrete public void processAnAnimal(String type) { AnimalFactory fac = new AnimalFactory(); … Animal oneAnimal = fac.create(type); … oneAnimal.sleep(); oneAnimal.makeSound(); oneAnimal.lookForFood(): … } Type specifi- cation is a parameter

DCS – SWC 16 Being less concrete public void processAnAnimal (String type, AnimalFactory fac) { Animal oneAnimal = fac.create(type); … oneAnimal.sleep(); oneAnimal.makeSound(); oneAnimal.lookForFood(): … } Type specifi- cation and object factory are parameters

DCS – SWC 17 Being less concrete This pattern is known as Simple Factory We have separated code for producing objects, and code for processing objects Processing code only knows about the interface Fewer responsibilities per class – ”Classes should only have one reason to change”

DCS – SWC 18 Abstraction to the next level The processing code needs a parameter which carries the type information for the object being created However, we also suggested that the factory itself could be a parameter Why would we do that….?

DCS – SWC 19 Abstraction to the next level public void processAnAnimal (String type, AnimalFactory fac) { Animal oneAnimal = fac.create(type); … oneAnimal.sleep(); oneAnimal.makeSound(); oneAnimal.lookForFood(): … } Type specifi- cation and object factory are parameters

DCS – SWC 20 Abstraction to the next level Consider a word processor: –A document is composed of various typo- graphic objects, like Heading, Emphasis, and so on –All such classes implement the interface Typo –Given some input source, a piece of code must produce a list of Typo objects

DCS – SWC 21 Abstraction to the next level // Part of input processing code TypoFactory theTypoFactory; public void createDocument(DocInput in) { ArrayList doc = new ArrayList (); while (in.hasNext()) { TypoInput tyIn = in.next(); Typo typ = makeTypo(tyIn); doc.add(typ); }

DCS – SWC 22 Abstraction to the next level // Part of input processing code private Typo makeTypo(TypoInput in) { String text = in.getText(); String type = in.getType(); Typo theTypo = theTypoFactory.create(type); thetypo.addText(text); return theTypo; }

DCS – SWC 23 Abstraction to the next level // TypoFactory code private Typo create(String type) { if (type.equals(”Heading”)) return new Heading(); else if (type.equals(”Emphasis”)) return new Emphasis();... else return null; }

DCS – SWC 24 Abstraction to the next level The code processing the input does not know about concrete Typo classes – good But the code is still ”constrained”… What is a Typo object really – it is a ”binding” between a text and a certain way of formatting the text Different concrete Typo classes provide different bindings

DCS – SWC 25 Abstraction to the next level A Heading might be –Font size 24 –Bold –Calibri font An Emphasis might be –Bold –Red font color

DCS – SWC 26 Abstraction to the next level A Typo factory thus defines a set of bindings between text and formatting – a layout What if we wish to change the layout of a document? We could then just define a different Typo factory, with different bindings

DCS – SWC 27 Abstraction to the next level // Part of input processing code TypoFactoryFormalLayout theTypoFactory; public void createDocument(DocInput in) { ArrayList doc = new ArrayList (); while (in.hasNext()) { TypoInput tyIn = in.next(); Typo typ = makeTypo(tyIn); doc.add(typ); } Just change the type of the Typo factory…

DCS – SWC 28 Abstraction to the next level This solution is still quite static Changing to a different factory requires code modification Why not use interfaces once again! We could also define an interface for the factory side, making the processing code independent of a specific factory

DCS – SWC 29 Abstraction to the next level Typo addText() TypoFactory Typo create(…)

DCS – SWC 30 Abstraction to the next level TypoTypoFactory TypoFactory- FormalLayout TypoFactory- SmartLayout

DCS – SWC 31 Abstraction to the next level TypoTypoFactory TypoHeading- Formal TypoEmphasis- Formal TypoHeading- Smart TypoEmphasis- Smart

DCS – SWC 32 Abstraction to the next level TypoHeading- Formal TypoEmphasis- Formal TypoHeading- Smart TypoEmphasis- Smart TypoFactory- FormalLayout TypoFactory- SmartLayout

DCS – SWC 33 Abstraction to the next level The factory for Formal layout only knows the concrete classes TypoHeading- Formal and TypoEmphasisFormal The factory for Smart layout only knows the concrete classes TypoHeadingSmart and TypoEmphasisSmart The factory interface only knows about the Typo interface

DCS – SWC 34 Abstraction to the next level // A configurable document creator class public class DocumentCreator { TypoFactory typoFac; public DocumentCreator(TypoFactory typoFac) { this.typoFac = typoFac; } public void createDocument(DocInput in) {...} }

DCS – SWC 35 Abstraction to the next level public void createFormalDocument() { TypoFactory typoFac = new TypoFactoryFormalLayout(); DocumentCreator docCre = new DocumentCreator(typoFac); docCre.createDocument(getDocInput()); }

DCS – SWC 36 Abstraction to the next level Note that the only thing that changes between two TypoFactory implementa- tions is the create method We may include concrete methods in the Typo interface – making it an abstract class – if it makes sense This is known as the Factory Mehtod pattern

DCS – SWC 37 The Factory method pattern Product Factory create() someMethod() ConcreteFactory create() ConcreteProduct

DCS – SWC 38 The Abstract Factory Our code can now work with different concrete factories, through a Factory interface What if we need to create several types of ”products”, not just a single type? –Typo – formattings of text –Graphic – formattings of graphic objects

DCS – SWC 39 The Abstract Factory Answer seems simple: just use Factory Method pattern twice TypoTypoFactory TypoFactory- FormalLayout TypoFactory- SmartLayout GraphicGraphicFactory GraphicFactory- FormalLayout GraphicFactory- SmartLayout

DCS – SWC 40 The Abstract Factory This looks fine… …but does it reflect our intention? Would it make sense to have a document, with –text using Formal layout –graphics using Smart layout Model does not include any ”binding” between related products

DCS – SWC 41 The Abstract Factory public void createFormalDocument() { TypoFactory tFac = new TypoFactoryFormalLayout(); GraphicFactory gFac = new GraphicFactorySmartLayout(); DocumentCreator docCre = new DocumentCreator(tFac,gFac); docCre.createDocument(getDocInput()); } Oooppss!

DCS – SWC 42 The Abstract Factory A Typo and a Graphic are not – as seen from a type point-of-view – related Would be somewhat artificial – or perhaps even impossible – to introduce a common base class However, we can enforce the binding through a shared factory class!

DCS – SWC 43 The Abstract Factory DocItemFactory createTypo() createGraphic() FormalDocItemFactorySmartDocItemFactory

DCS – SWC 44 The Abstract Factory public void createFormalDocument() { DocItemFactory fac = new FormalDocItemFactory (); DocumentCreator docCre = new DocumentCreator(fac); docCre.createDocument(getDocInput()); }

DCS – SWC 45 The Abstract Factory public void createDocument(DocInput in) {... Typo aTypo = theFactory.createTypo(typoInfo);... Graphic aGraphic = theFactory.createGraphic(graphicInfo);... } Using the same factory for creating Typo and Graphic objects!

DCS – SWC 46 The Abstract Factory This pattern is known as the Abstract Factory pattern By making a creator class with several create… methods, we restrict the product combinations the client can create

DCS – SWC 47 The Abstract Factory The methods in the Abstract Factory are product-type dependent, so if we add another product, we need to change the interface of the base class This is a price we must pay for binding (formally) non-related types together Patterns are also compromises…