Design Patterns David Talby. This Lecture n The Creational Patterns u Builder u Prototype u Factory Method u (Abstract Factory) u Singleton n Choosing.

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

Welcome to. Who am I? A better way to code Design Patterns ???  What are design patterns?  How many are there?  How do I use them?  When do I use.
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.
Design Patterns David Talby. This Lecture Representing other objects Proxy, Adapter, Façade Re-routing method calls Chain of Responsibility Coding partial.
Design Patterns Copyright © Vyacheslav Mukhortov, Nikita Nyanchuk-Tatarskiy, Copyright © INTEKS LLC,
Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Prototype Pattern Intent:
Design Patterns David Talby. This Lecture n The Creational Patterns u Abstract Factory u Builder u Prototype u Factory Method n Choosing Between Them.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Prototype Creational Design Pattern By Brian Cavanaugh September 22, 2003 Software, Design and Documentation.
Design Patterns David Talby. This Lecture n What is it all about? n Abstract Factory n Composite n Strategy.
Design Patterns David Talby. This Lecture n The rest of the pack u Working over a network F Proxy, State, Chain of Responsibility u Working with external.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Design Patterns David Talby. This Lecture n Re-Routing Method Calls u Proxy, Chain of Responsibility n Working with external libraries u Adapter, Façade.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns II.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
Creational Patterns (1) CS350, SE310, Fall, 2010.
Abstract Factory Design Pattern making abstract things.
Creational Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns III.
Software Components Creational Patterns.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Design Principle & Patterns by A.Surasit Samaisut Copyrights : All Rights Reserved.
Object Oriented Design David Talby. Welcome! n Introduction n UML u Use Case Diagrams u Interaction Diagrams u Class Diagrams n Design Patterns u Composite.
ECE450S – Software Engineering II
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.
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.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
FACTORY METHOD. Design Pattern Space Purpose ScopeCreationalStructuralBehavioral ClassFactory MethodAdapterInterpreter Template Method ObjectAbstract.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
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 SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
Singleton Pattern Presented By:- Navaneet Kumar ise
07 - Creational (3)CSC4071 Builder Separate the construction of a complex object from its representation so that the same construction process can create.
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.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
SOFTWARE DESIGN Design Patterns 1 6/14/2016Computer Science Department, TUC-N.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
March 10, 2007 Design Patterns David Talby.
1/23/2018 Design Patterns David Talby.
Abstract Factory Pattern
Design Patterns Spring 2017.
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Factory Patterns 1.
Creational Design Patterns
Creational Patterns (2)
Abstract Factory Pattern
Intent (Thanks to Jim Fawcett for the slides)
Ms Munawar Khatoon IV Year I Sem Computer Science Engineering
Creational Patterns.
Object Oriented Design
Presentation transcript:

Design Patterns David Talby

This Lecture n The Creational Patterns u Builder u Prototype u Factory Method u (Abstract Factory) u Singleton n Choosing Between Them

Creational Patterns n Easily Change: u What gets created? u Who creates it? u When is it created? n Hide the concrete classes that get created from client code n Competing patterns, each with its own strengths

4. Builder n Separate the specification of how to construct a complex object from the representation of the object n For example, a converter reads files from one file format n It should write them to one of several output formats

The Requirements n Single Choice Principle u Same reader for all output formats u Output format chosen once in code n Open-Closed Principle u Easy to add a new output format u Addition does not change old code n Dynamic choice of output format

The Solution n We should return a different object depending on the output format: u HTMLDocument, RTFDocument, … n Separate the building of the output from reading the input n Write an interface for such a builder n Use inheritance to write different concrete builders

The Solution II n Here’s the builder’s interface: class Builder { void writeChar(char c) { } void s etFont(Font *f) { } void newPage() { } }

The Solution III n Here’s a concrete builder: class HTMLBuilder : public Builder { private: HTMLDocument *doc; public: HTMLDocument *getDocument() { return doc; } // all inherited methods here }

The Solution IV n The converter uses a builder: class Converter { void convert( Builder *b) { while (t = read_next_token() ) switch (o.kind) { CHAR: b->writeChar(o); FONT: b->setFont(o); // other kinds… }

The Solution V n This is how the converter is used: RTFBuilder *b = new RTFBuilder; converter->convert(b); RTFDocument *d = b->getDocument();

The UML

The Fine Print n The builder’s interface affects the ease of coding concrete builders n Kinds of documents don’t need a common base class n Methods in class Builder are empty and not abstract n getResult() is not always trivial u Optimizations u Lazy Creation

Known Uses n Converting to different formats n Building a parse tree in a compiler n Building a normalized database

5. Prototype n Specify the kind of object to create using a prototypical instance n For example, a photo/map editor has a palette of tools and objects that can be created n How do we have only one class for creations, and parameterize it by the class of objects it initializes?

The Requirements n One class for the creation tool n Easy to add new objects n Dynamic toolbox configuration

The Solution n Hold a prototype of object to create n Creation is by cloning the prototype

The Solution II n Less classes in the system n Can be even less: same Graphic object with different properties can be used for different tools n Tools can be chosen and configured at runtime

The UML

The Fine Print n Prototype Manager - a runtime registry of prototype can handle dynamically linked classes n Java, SmallTalk, Eiffel provide a default clone() method. C++ has copy constructors n All of these are shallow by default n When implementing deep clone, beware of circular references!

Known Uses n Toolboxes / Palettes n Supporting dynamically defined debuggers in a uniform GUI n EJB / COM Servers n Basically a plug-in mechanism

6. Factory Method n Let subclasses decide which objects to instantiate n For example, a framework for a windowing application has a class Application which must create an object of class Document n But the actual applications and documents are not written yet!

The Solution n Separate creation into a method

Second Variant n A remote services package has a RemoteService class that returns objects of class Proxy to client n A few clients wish to write a more potent CachedProxy n How do we support this without much hassle?

Second Variant Solution n Separate creation into a method n RemoteService will have a virtual method called CreateProxy() n Write CachedProxy, then write: class CachedRemoteService : public RemoteService { Proxy* createProxy(...) { return new CachedProxy(...); }

The UML

The Fine Print n Two Variants: Is the factory method abstract or not? n Good style to use factory methods even for a slight chance of need n Parameterized factory methods make it easy to add created products without affecting old code Product* createProduct(int id) { switch (id) {... } }

The Fine Print II n C++ warning: You can’t call a factory method from a constructor! u Use lazy initialization instead Product* getProduct() { if (_product == NULL) _product = createProduct(); return _product; } n Use templates to avoid subclassing u Application u complex, complex

Known Uses n A very common pattern n Framework classes u Application, Document, View,... n Changing default implementations u Proxy, Parser, MemoryManager, …

Pattern of Patterns n Encapsulate the varying aspect n Interfaces n Inheritance describes variants n Composition allows a dynamic choice between variants Criteria for success: Open-Closed Principle Single Choice Principle

A Comparative Example

The Example Problem Maze* MazeGame::CreateMaze () { Maze* aMaze = new Maze; Room* r1 = new Room(1); Room* r2 = new Room(2); Door* theDoor = new Door(r1, r2); aMaze->AddRoom(r1); aMaze->AddRoom(r2); r1->SetSide(North, new Wall); r1->SetSide(East, theDoor); // set other sides, also for r2 return aMaze; }

Enchanted Mazes n How do we reuse the same maze with EnchantedRoom, TrapDoor? u Pass createMaze an object that can create different maze parts u Pass createMaze an object that can build a maze and then return it u Pass createMaze initialized samples of each kind of maze part u Move creation with new to other methods that descendants redefine

1. Abstract Factory n Define a set of interfaces u Door, Wall, Room,... n Write families of classes u SimpleDoor, SimpleRoom, … u EnchantedDoor, EnchantedRoom,... n Define an abstract MazeFactory, and a concrete class for each family u SimpleFactory, EnchantedFactory, … n Pass createMaze a factory

Abstract Factory II Maze* MazeGame::CreateMaze (MazeFactory* mf) { Maze* aMaze = mf->createMaze(); Room* r1 = mf->createRoom(1); Room* r2 = mf->createRoom(2); Door* d = mf->createDoor(r1,r2); // rest is same as before n Families don’t have to be disjoint n Same factory can return variants of the same class

Abstract Factory Cons n Requires a new factory class for every family n Families are defined statically n Parts of the complex maze are returned right after creation n The client of the factory builds the connections between maze parts n Maze stands for any complex object

Builder Pros & Cons n Pros u Each builder can create a totally different kind of object u Object returned only at the end of construction - enables optimization u Especially if object is on network n Cons u Complex Interface to builder

Prototype Pros & Cons n Pros u Less Classes u Prototype can be customized between different creations n Cons u Requires memory to hold prototype u Many prototypes must be passed u Clone() may be hard to implement

Factory Method P&C n Pros u The simplest design n Cons u Requires a new class for every change in creation u Compile-time choice only

The Verdict n Use Factory Methods when there is little (but possible) chance of change n Use Abstract Factory when different families of classes are given anyway n Use Prototype when many small objects must be created similarly n Use Builder when different output representations are necessary

Some Easy Cases n Dynamic loading of classes whose objects must be created u only Prototype n Creation can be highly optimized once entire structure is known u only Builder

7. Singleton n Ensure that only one instance of a class exists, and provide a global access point to it n For example, ensure that there’s one WindowManager, FileManager or PrintSpooler object in the system n Desirable to encapsulate the instance and responsibility for its creation in the class

The Solution n O-O languages support methods shared by all objects of a class u static in C++ and Java u class methods in SmallTalk, Delphi n The singleton class has a reference to its single instance n The instance has a getter method which initializes it on the first request n The class’s constructor is protected to prevent creating other instances

The Solution class Spooler { public: static Spooler* instance() { if (_instance == NULL) _instance = new Spooler(); return _instance; } protected: Spooler() {... } private: static Spooler* _instance = 0; }

The UML

The Fine Print n Passing arguments for creation can be done with a create(...) method n Making the constructor public makes it possible to create other instance except the “main” one u Not a recommended style n instance() can manage concurrent access or manage a list of instances n Access to singletons is often a bottleneck in concurrent systems

Known Uses n Every system has singletons! n WindowManager, PrinterManager, FileManager, SecurityManager,... n Class Application in a framework n Log and error reporting classes n With other design patterns

Summary: Connections n “Abstract Factories are usually implemented using Factory Methods but can also use Prototypes” n “Builders and Abstract Factories are often Singletons” n “Builders can use Abstract Factories to enjoy best of both worlds”