1 Creational Patterns CS 236700: Software Design Winter 2004-2005/T8.

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, Abstract Factory, Builder Billy Bennett June 11, 2009.
Copyright © Active Frameworks Inc. - All Rights Reserved - V2.0Creational Patterns - Page L4-1 PS95&96-MEF-L11-1 Dr. M.E. Fayad Creationa l Paradigm.
Plab – Tirgul 12 Design Patterns
. Plab – Tirgul 12 Design Patterns. Design Patterns u The De-Facto Book on Design Patterns:
5/08 What is a Design Pattern „Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the.
Prototype Pattern Creational Pattern Specify the kinds of objects to create using a prototypical instance, and create new objects by copy this prototype.
Nov, 1, Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven solution to a recurring problem in a specific context and its.
Design Pattern Course Builder Pattern 1 Mahdieh Monzavi AmirKabir University of Technology, Department of Computer Engineering & Information Technology.
Design Patterns I 1. Creational Pattern Singleton: intent and structure Ensure a class has one instance, and provide a global point of access to it 2.
Prototype Pattern Intent:
Oct, 16, Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven solution to a recurring problem in a specific context and.
DESIGN PATTERNS Redesigning Applications And
Design Patterns Examples in C++ Moshe Fresko Bar-Ilan University Object Oriented Programming
Creational Patterns: The Abstract Factory CSE 335 Spring 2008 E. Kraemer.
Prototype Creational Design Pattern By Brian Cavanaugh September 22, 2003 Software, Design and Documentation.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Abstract Factory Pattern.
Builder A Creational Design Pattern A Presentation by Alex Bluhm And.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Design Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns II.
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
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.
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.
SWE 316: Software Design and Architecture – Dr. Khalid Aljasser Objectives Lecture 13 Creational Design Pattern SWE 316: Software Design and Architecture.
DESIGN PATTERNS Sanjeeb Kumar Nanda 30-Aug What is a pattern? Pattern is a recurring solution to a standard problem Each Pattern describes a problem.
Prototype pattern Participants Prototype (Graphic) – declared an interface for cloning itself ConcretePrototype (EditBox, Slider) – implements an operation.
CS 590L – Distributed Component Architecture 02/20/2003Uttara Paingankar1 Design Patterns: Factory Method The factory method defines an interface for creating.
Design Pattern. Definition: A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
1 Prototype Design Pattern Nitin Prabhu Adapted from presentations of Mike Fortozo,John Lin
Creational Design Patterns Yaodong Bi December 21, 2015December 21, 2015December 21, 2015.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
Singleton Pattern Presented By:- Navaneet Kumar ise
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
Reference – Object Oriented Software Development Using Java - Jia COP 3331 Object Oriented Analysis and Design Chapter 10 – Patterns Jean Muhammad.
 Creational design patterns abstract the instantiation process.  make a system independent of how its objects are created, composed, and represented.
The Abstract Factory Pattern (Creational) ©SoftMoore ConsultingSlide 1.
S.Ducasse Stéphane Ducasse 1 Abstract Factory.
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.
SOFTWARE DESIGN Design Patterns 1 6/14/2016Computer Science Department, TUC-N.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Abstract Factory Pattern
Factory Method Pattern
Design Pattern Catalogues
Factory Patterns 1.
Design Patterns Lecture 1
Software Design and Architecture
Creational Design Patterns
Factory Method Pattern
Abstract Factory Pattern
Intent (Thanks to Jim Fawcett for the slides)
What is a Design Pattern
Design Patterns - A few examples
Software Engineering Lecture 7 - Design Patterns
UNIT-III Creational Patterns UNIT-III.
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
Lesson 5: More on Creational Patterns
Creational Patterns.
Presentation transcript:

1 Creational Patterns CS : Software Design Winter /T8

2 Singleton: intent Ensure a class has one instance, and provide a global point of access to it

3 Singleton: structure Singleton static uniqueInstance data static instance() singletonOperation() getData() return uniqueInstance

4 Singleton: applicability + participants  Use the Singleton pattern when there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code  Participants Singleton defines an instance() operation that lets clients access its unique instance. Instance is a class operation (i.e.: static) may be responsible for creating its own unique instance

5 Singleton: consequences  Controlled access to a sole instance  An elegant replacement for global variables  More flexible than static member functions Allows overriding The singleton may be extended to allow several instances

6 Singleton: implementation class Keyboard { private static Keyboard instance_ = new Keyboard(); public static Keyboard instance() { return instance_; } private Keyboard() { … } } class Keyboard { private static Keyboard instance_ = new Keyboard(); public static Keyboard instance() { return instance_; } private Keyboard() { … } }

7 Factory Method: intent Define an interface for creating an object, but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses. Define an interface for creating an object, but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses.

8 Factory Method: motivation Document doc = createDocument(); docs.add(doc); doc.open(); Application createDocument() newDocument() openDocument() Document save() print() docs MyDocument MyApplication createDocument() creates return new MyDocument()

9 Factory Method: motivation (cont.)  Application class is responsible for creation (and management) of Documents  Problem: Application class knows: WHEN a new document should be created Application class doesn’t know: WHAT KIND of document to create  Solution: Application defines a virtual function, createDocument() MyApplication makes sure that createDocument() will create a product ( Document ) of the correct type.

10 Factory Method: participants  Product (Document) defines the interface of objects the factory method creates  ConcreteProduct (MyDocument) implements the Product interface  Creator (Application) declares the factory method, which returns an object of type Product. May also define a default implementation of the factory method that returns a default ConcreteProduct object.  ConcreteCreator (MyApplication) overrides the factory method to return an instance of a ConcreteProduct

11 Factory Method: structure Product ConcreteProduct Creator factoryMethod() AnOperation() ConcreteCreator factoryMethod() creates... product= factoryMethod()... return new ConcreteProduct

12 Factory Method: consequences  Advantage Concrete (Dynamic) types are isolated from the client code => Reduced level of Deja-vu.  Provides hooks for subclasses A standard technique for subclasses to affect their parents' behavior  Connects parallel class hierarchies see next slide for example  Potential disadvantage clients might have to subclass the Creator class just to create a particular (i.e., 1) ConcreteProduct object

13 Connecting parallel hierarchies LineFigure CreateManipulator() TextFigure CreateManipulator() LineManipulator DownClick() Drag() TextManipulator DownClick() Drag() Manipulator DownClick() Drag() Client Figure CreateManipulator() creates Localizes knowledge of which classes belongs together

14 Factory Method: 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 object 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

15 Factory Method: implementation  Two major varieties Creator declares ABSTRACT factory method, ConcreteCreator implements it Creator defines a default implementation for factory method  Parameterized factory methods lets the factory method to create multiple kinds of objects factory methods takes a parameter: a kind of object to create all products have to share a Product interface

16 Abstract Factory: intent Provide an interface for creating families of related or dependent objects, without specifying their concrete classes

17 Abstract Factory: motivation MotifWidgetFactory CreateScrollBar() CreateWindow() PMWidgetFactory CreateScrollBar() CreateWindow() PMWindowMotifWindow PMScrollBarMotifScrollBar WidgetFactory (abstract) CreateScrollBar() CreateWindow() Window ScrollBar Client creates

18 Abstract Factory: applicability  Use the Abstract Factory pattern when A system should be independent of how its products are created Products are grouped into families A family is intended to be used together, and you need to enforce this constraint You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations

19 Abstract Factory: participants  AbstractFactory (WidgetFactory) declares an interface for operations that create abstract product objects  ConcreteFactory (MotifWidgetFactory,…) implements the operations to create concrete product objects  AbstractProduct (Window, ScrollBar) declared an interface for a type of product object  ConcreteProduct (MotifWindow, MotifScrollBar) defines a product object to be created by the corresponding concrete factory implements the AbstractProduct interface  Client uses only interfaces declared by AbstractFactory and AbstractProduct classes

20 Abstract Factory: structure ConcreteFactory1 CreateProductA() CreateProductB() ConcreteFactory2 CreateProductA() CreateProductB() ProductA2 ProductA1 ProductB2 ProductB1 AbstractFactory CreateProductA() CreateProductB() AbstractProductA AbstractProductB Client creates

21 Abstract Factory: consequences  Concrete (Dynamic) types are isolated from the client code  Exchanging a product family is easy  Reduced risk of mixing of families  Supporting new kinds of products is difficult AbstractFactory interface fixes the set of products that can be created involves changing AbstractFactory and all its subclasses interfaces

22 Abstract Factory: implementation  Factories as singletons  Creating the products use Factory Method pattern declare FactoryMethod for each kind of product in AbstractFactory override FactoryMethod in ConcreteFactory use Prototype pattern for ConcreteFactory if many product families are possible initialize the concrete factory with a prototypical instance of each product in the family concrete factory will create a new product by cloning the prototype no need for a new concrete factory class for each new family  Defining extensible factories Via parameterization -- I.e., object = factory.make ( typeA ) ; Via mixing concrete and abstract factory hierarchies.

23 Prototype: intent Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype

24 Prototype: motivation Tool manipulate() RotateTool manipulate() p = prototype.clone() while (user drags mouse) { p.draw(mouse_position) } insert p into drawing prototype GraphicTool manipulate() Graphic draw(position) clone() EditBox draw(position) clone() Slider draw(position) clone() return copy of self

25 Prototype: participants  Prototype (Graphic) declared an interface for cloning itself  ConcretePrototype (EditBox, Slider) implements an operation for cloning itself  Client (GraphicTool) creates a new object by asking a prototype to clone itself

26 Prototype: structure p = prototype->clone() Prototype clone() prototype Client operation() ConcretePrototype1 clone() ConcretePrototype clone() return copy of self

27 Prototype: applicability  Use the Prototype pattern when a system should be independent of how its products are created; and when the classes to instantiate are specified at run-time; or to avoid building a hierarchy of factories; or State of the created instance cannot be easily specified

28 Prototype pattern - consequences  Adding and removing prototypes at run-time  Specifying new objects by varying values By adding a new prototype you actually define a new 'type' which your program can instantiate  Reduced subclassing (See previous slide)  Pseudo Dynamic loading

29 Prototype: implementation  Simple prototyping: Client code must provide an existing prototype object  Using a prototype manager: The manager keeps a dictionary of available prototypes Client code can add/remove prototypes to/from the dictionary Instantiation: client code specifies a "key" value. The Manager duplicates the prototype matching this key  Implementing the clone() operation “shallow copy versus deep copy”

30 Builder: intent Separate the construction of a complex object from its representation so that the same construction process can create different representations

31 Builder: Motivation DocConverter buildResult() IMaker addLine(line) addImage(img) HtmlMaker addLine(line) addImage(img) getResult() PdfMaker addLine(line) addImage(img) getResult() while(parts.hasMore()) { t = parts.next(); switch(t.type) { case LINE: builder.addLine(t.line) case IMAGE: builder.addImage(t.img) }

32 Builder: motivation (cont.)  DocConverter is expected to convert a document to many output formats (html, pdf, etc…)  Number of possible conversions is open-ended.  The solution: Client code "loads" the appropriate maker object Whenever the DocConverter recognizes a complete element (either a line or an image), it issues a corresponding request to the IMaker object. At the end, client code issues a getResult() request on the active maker

33 Builder: participants  Builder (IMaker) Specifies an interface for creating/assembling parts of a product.  ConcreteBuilder (HtmlMaker, PdfMaker) Implements the Builder interface  Director (DocConverter) Constructs an object of an unknown type using the Builder interface  Product (HtmlDocument, PdfDocument) Complete object returned by invoking getResult() on the ConcreteBuilder

34 Builder: structure

35 Builder: consequences  Isolates code for construction and representation Construction logic is encapsulated within the director Product structure is encapsulated within the concrete builder => Lets you vary a product's internal representation  Supports fine control over the construction process Breaks the process into small steps

36 Builder: applicability  Use the Builder pattern when The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled. The construction process must allow different representations for the object that's constructed

37 Builder: implementation public interface IBuilder { void begin_node(); void end_node(); void add_data(String s); }; public Class TextBuilder impelements IBuilder { public void begin_node() { depth_ += 2; } public void end_node() { depth_ -= 2; } public void add_data(String s) { for(int i = 0; i < depth_; ++i) result_ += ‘ ‘; result_ += s + '\n‘; } public String result_ = ““ ; int depth_ = 0; }; public interface IBuilder { void begin_node(); void end_node(); void add_data(String s); }; public Class TextBuilder impelements IBuilder { public void begin_node() { depth_ += 2; } public void end_node() { depth_ -= 2; } public void add_data(String s) { for(int i = 0; i < depth_; ++i) result_ += ‘ ‘; result_ += s + '\n‘; } public String result_ = ““ ; int depth_ = 0; };

38 Builder: implementation public class Director { void set_builder(IBuilder b) { b_ = b; } void process(Node r) { if(r == null) return; b_.begin_node(); b_.add_data(r.val_); process(r.first_); b_.end_node(); process(r.next_); } IBuilder b_; }; public class Director { void set_builder(IBuilder b) { b_ = b; } void process(Node r) { if(r == null) return; b_.begin_node(); b_.add_data(r.val_); process(r.first_); b_.end_node(); process(r.next_); } IBuilder b_; }; static void main() { Node root; Director dir; TextBuilder tb; … dir.set_builder(tb); dir.process(root); String s = tb.result_; System.out.print(s); } static void main() { Node root; Director dir; TextBuilder tb; … dir.set_builder(tb); dir.process(root); String s = tb.result_; System.out.print(s); }

39 Builder: implementation  The Builder interface (IMaker) Must be general enough to allow construction of many products  Abstract base class for all products? Usually not feasible (products are highly different)  Default implementation for methods of Builder? "Yes": May decrease amount of code in ConcreteBuilder s "No:" May introduce silent bugs