GoF Design Pattern Categories

Similar documents
GoF Design Pattern Categories

Creational Patterns. Factory Method (FM) Abstract Factory (AF) Singleton (SI) Prototype (PR) Builder (BU)

Design Pattern- Creational pattern 2015

Laboratorio di Progettazione di Sistemi Software Design Pattern Creazionali. Valentina Presutti (A-L) Riccardo Solmi (M-Z)

Design Patterns. Manuel Mastrofini. Systems Engineering and Web Services. University of Rome Tor Vergata June 2011

Software Quality Management

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

Factory Method Pattern Creational. » Define an interface for creating an object but lets subclasses decide the specific class to instantiate

Software Design COSC 4353/6353 D R. R A J S I N G H

Object-Oriented Design

SDC Design patterns GoF

Object-Oriented Oriented Programming Factory Method Pattern Abstract Factory Pattern. CSIE Department, NTUT Woei-Kae Chen

What is Design Patterns?

What is Design Patterns?

Design Patterns. GoF design patterns catalog

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

Material and some slide content from: - GoF Design Patterns Book. Design Patterns #1. Reid Holmes. Lecture 11 - Tuesday October

Design Pattern. CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.)

Object Oriented Design. - Defines an instance for creating an object but letting subclasses decide which class to instantiate

Design Pattern What is a Design Pattern? Design Pattern Elements. Almas Ansari Page 1

Design Patterns Reid Holmes

Keywords: Abstract Factory, Singleton, Factory Method, Prototype, Builder, Composite, Flyweight, Decorator.

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Creational Patterns. George Blankenship

Dr. Xiaolin Hu. Review of last class

The GoF Design Patterns Reference

Using Design Patterns in Java Application Development

INSTITUTE OF AERONAUTICAL ENGINEERING

Creational Design Patterns

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

Design Patterns. An introduction

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming

What is Design Patterns?

Design Patterns. Hausi A. Müller University of Victoria. Software Architecture Course Spring 2000

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout

Software Design Patterns. Background 1. Background 2. Jonathan I. Maletic, Ph.D.

CSCI 253. Overview. The Elements of a Design Pattern. George Blankenship 1. Object Oriented Design: Template Method Pattern. George Blankenship

Software Design COSC 4353/6353 D R. R A J S I N G H

Brief Note on Design Pattern

EPL 603 TOPICS IN SOFTWARE ENGINEERING. Lab 6: Design Patterns

A Reconnaissance on Design Patterns

Object-Oriented Oriented Programming

Design of Software Systems (Ontwerp van SoftwareSystemen) Design Patterns Reference. Roel Wuyts

UNIT I Introduction to Design Patterns

» Reader for RTF (Rich Text Format) should be able to convert to any other representation Plain Text, MIF (Maker Interchange File), Postscript

Lecture 13: Design Patterns

OODP Session 4. Web Page: Visiting Hours: Tuesday 17:00 to 19:00

Pattern Resources. Lecture 25: Design Patterns. What are Patterns? Design Patterns. Pattern Languages of Programming. The Portland Pattern Repository

An Introduction to Patterns

Department of Information Technology

DESIGN PATTERN - INTERVIEW QUESTIONS

CS 2720 Practical Software Development University of Lethbridge. Design Patterns

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Object-oriented Software Design Patterns

UNIT I Introduction to Design Patterns

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

CSE870: Advanced Software Engineering (Cheng) 1

Produced by. Design Patterns. MSc in Communications Software. Eamonn de Leastar

Introduction to Software Engineering: Object Design I Reuse & Patterns

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

Design Patterns. Softwaretechnik. Matthias Keil. Albert-Ludwigs-Universität Freiburg

DESIGN PATTERNS SURESH BABU M ASST PROFESSOR VJIT

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

A few important patterns and their connections

Plan. A few important patterns and their connections. Singleton. Singleton: class diagram. Singleton Factory method Facade

Design Patterns. Software Engineering. Sergio Feo-Arenis slides by: Matthias Keil

Design Patterns #3. Reid Holmes. Material and some slide content from: - GoF Design Patterns Book - Head First Design Patterns

Creational Patterns for Variability

Design Pattern and Software Architecture: IV. Design Pattern

Prototype Pattern Creational

Design Patterns. SE3A04 Tutorial. Jason Jaskolka

The Strategy Pattern Design Principle: Design Principle: Design Principle:

Lecture 20: Design Patterns II

Tuesday, October 4. Announcements

CHAPTER 6: CREATIONAL DESIGN PATTERNS

Software Reengineering Refactoring To Patterns. Martin Pinzger Delft University of Technology

CSCI Object Oriented Design: Frameworks and Design Patterns George Blankenship. Frameworks and Design George Blankenship 1

Softwaretechnik. Design Patterns. Matthias Keil. Albert-Ludwigs-Universität Freiburg

Prototype Pattern Creational

Object Oriented Methods with UML. Introduction to Design Patterns- Lecture 8

Applying Design Patterns to SCA Implementations

Idioms and Design Patterns. Martin Skogevall IDE, Mälardalen University

Topics in Object-Oriented Design Patterns

COSC 3351 Software Design. Design Patterns Structural Patterns (I)

CSCD01 Engineering Large Software Systems. Design Patterns. Joe Bettridge. Winter With thanks to Anya Tafliovich

Design Patterns. Dr. Rania Khairy. Software Engineering and Development Tool

Slide 1. Design Patterns. Prof. Mirco Tribastone, Ph.D

Softwaretechnik. Design Patterns. Stephan Arlt SS University of Freiburg. Stephan Arlt (University of Freiburg) Softwaretechnik SS / 47

Object-Oriented Design

Software Engineering Prof. Rushikesh K.Joshi IIT Bombay Lecture-15 Design Patterns

Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns

Design Patterns. CSE870: Advanced Software Engineering (Design Patterns): Cheng

2.1 Design Patterns and Architecture (continued)

APPLYING DESIGN PATTERNS TO SCA IMPLEMENTATIONS

ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns

Overview of Patterns: Introduction

CS/CE 2336 Computer Science II

Information systems modelling UML and service description languages

Factory Method. Comp435 Object-Oriented Design. Factory Method. Factory Method. Factory Method. Factory Method. Computer Science PSU HBG.

EMBEDDED SYSTEMS PROGRAMMING Design Patterns

Tecniche di Progettazione: Design Patterns

Transcription:

GoF Design Pattern Categories Purpose Creational Structural Behavioral Scope Class Factory Method Adapter Interpreter Template Method Object Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Facade Proxy Flyweight Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor 1

Intent: BUILDER (Object Creational) Separate the construction of a complex object from its representation so that the same construction process can create different representations Builders specify abstract interfaces for creating parts of a Product object 2

BUILDER (Object Creational) Usage: Rarely used, only useful if complex objects consisting of multiple parts need to be constructed (composite objects for example) 3

BUILDER (Object Creational) Motivation: ortf reader should be able to convert RTF to many text format oadding new conversions without modifying the reader should be easy 4

Builder Motivation Each kind of converter class takes the mechanism for creating and assembling a complex object and puts it behind an abstract interface. The converter is separate from the reader, which is responsible for parsing an RTF document. The Builder pattern captures all these relationships. Each converter class is called a builder in the pattern, and the reader is called the director. 5

Builder motivation 6

Builder motivation (example) 7

Builder Motivation Applied to this example, the Builder pattern separates the algorithm for interpreting a textual format (that is, the parser for RTF documents) from how a converted format gets created and represented. This lets us reuse the RTFReader's parsing algorithm to create different text representations from RTF documents just configure the RTFReader with different subclasses of Textconverter. 8

Applicability Use the Builder pattern when othe algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled othe construction process must allow different representations for the object that is constructed 9

BUILDER Structure Director Construct () builders Builder BuildPart () for all objects in structure { builder->buildpart () } ConcreteBuilder BuildPart () GetResult () Product 10

Builder - participants Builder (TextConverter): - specifies an abstract interface for creating parts of a Product object. ConcreteBuilder (ASCIIConverter, TeXConverter, TextWidgetConverter) - constructs and assembles parts of the product by implementing the Builder interface. - defines and keeps track of the representation it creates. - provides an interface for retrieving the product (e.g., GetASCIIText, Get-TextWidget). 11

Builder - participants Director (RTFReader) - constructs an object using the Builder interface. Product (ASCIIText, TeXText, TextWidget) - represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled. - includes classes that define the constituent parts, including interfaces for assembling the parts into the final result. 12

Builder - Collaborations Client creates Director object and configures it with the desired Builder object Director notifies Builder whenever a part of the product should be built Builder handles requests from the Director and adds parts to the product Client retrieves the product from the Builder 13

Builder - Collaborations 14

Consequences It lets you vary a product's internal representation. It isolates code for construction and representation. It gives you finer control over the construction process. 15

Implementation issues Assembly and construction interface. Why no abstract class for products? Empty methods as default in Builder. 16

Related Patterns Abstract Factory is similar to Builder in that it too may construct complex objects. The primary difference is that the Builder pattern focuses on constructing a complex object step by step. Abstract Factory's emphasis is on families of product objects (either simple or complex). 17

Related Patterns Builder returns the product as a final step, but as far as the Abstract Factory pattern is concerned, the product gets returned immediately. A Composite is what the builder often builds. 18

Known Uses RTF converter application is from ET++. Builder is a common pattern in Smalltalk-80. The Service Configurator framework from the Adaptive Communications Environment uses a builder to construct network service components that are linked into a server at run-time. 19

20

A scenario You ve just been asked to build a vacation planner for Patternsland, a new theme park just outside of Objectville. Park guests can choose a hotel and various types of admission tickets, make restaurant reservations, and even book special events. To create a vacation planner, you need to be able to create structures like this: 21

22

23

24

enum VehicleType { Car, MotorCycle} ------------------------------------------------ enum Wheels {Wheels_2, Wheels_3, Wheels_4 } ----------------------------------------- enum Door { Door_0, Door_2, Door_4} ---------------------------------- enum Frame { Car_Frame, MotorCycle_Frame } ------------------------- enum Engine { Car_Engine_2500CC, MotorCycle_Engine_50CC} 26

class Vehicle { //product public Vehicle(VehicleType VType) } { this.vtype = VType; } public VehicleType VType; public Engine engin; public Wheels wheels; public Door door; public Frame frame; 27

abstract class VehicleBuilder { protected Vehicle NewVehicle; } public Vehicle GetVehicle() { return NewVehicle; } public abstract void BuildFrame(); public abstract void BuildWheels(); public abstract void BuildDoor(); public abstract void BuildEngine(); 28

class CarBuilder:VehicleBuilder //concrete builder { public CarBuilder() } { NewVehicle = new Vehicle(VehicleType.Car); } public override void BuildDoor() { NewVehicle.door = Door.Door_4; } public override void BuildFrame() { NewVehicle.frame = Frame.Car_Frame; } public override void BuildWheels() { NewVehicle.wheels = Wheels.Wheels_4; } public override void BuildEngine() { NewVehicle.engin = Engine.Car_Engine_2500CC; } 29

class MotorCycle:VehicleBuilder { public MotorCycle() } { NewVehicle = new Vehicle(VehicleType.MotorCycle); } public override void BuildDoor() { NewVehicle.door = Door.Door_0; } public override void BuildEngine() { NewVehicle.engin = Engine.MotorCycle_Engine_50CC; } public override void BuildWheels() { NewVehicle.wheels = Wheels.Wheels_2; } public override void BuildFrame() { NewVehicle.frame = Frame.MotorCycle_Frame; } 30

class Shop //director { public void ConStruct(VehicleBuilder VB) } { } VB.BuildFrame(); VB.BuildEngine(); VB.BuildWheels(); VB.BuildDoor(); 31

private void button1_click(object sender, EventArgs e) { VehicleBuilder builder = new CarBuilder(); } Shop shop = new Shop(); shop.construct(builder); Vehicle c = builder.getvehicle(); MessageBox.Show(c.VType.ToString()); //output=car 32

FACTORY METHOD (Class Creational) Intent: o Define an interface for creating an object, but let subclasses decide which class to instantiate. o Factory Method lets a class defer instantiation to subclasses. Also Known As Virtual Constructor 33

FACTORY METHOD (Class Creational) Usage: Frequently used, fairly easy to implement and useful for centralizing object lifetime management and avoiding object creation code duplication 34

FACTORY METHOD (Class Creational) Motivation: o Framework use abstract classes to define and maintain relationships between objects o Framework has to create objects as well - must instantiate classes but only knows about abstract classes - which it cannot instantiate o Factory method encapsulates knowledge of which subclass to create - moves this knowledge out of the framework 35

FACTORY METHOD Motivation Document docs Application Open() Close() Save() Revert() CreateDocument() NewDocument() OpenDocument() Document* doc=createdocument(); docs.add(doc); doc->open(); MyDocument MyApplication CreateDocument() return new MyDocument 36

Applicability Use the Factory Method pattern when oa class can t anticipate the class of objects it must create. oa class wants its subclasses to specify the objects it creates. oclasses delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate. 37

FACTORY METHOD structure (Class Creational) 38

39

Product Participants o Defines the interface of objects the factory method creates ConcreteProduct o Implements the product interface Creator o Declares the factory method which returns object of type product o May contain a default implementation of the factory method o Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate Concrete Product. ConcreteCreator o Overrides factory method to return instance of ConcreteProduct 40

Collaborations Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate Concrete Product. 41

Provides hooks for subclasses. Consequences Connects parallel class hierarchies. 42

Implementation Two major varieties. Parameterized factory methods. Language-specific variants and issues. Using templates to avoid subclassing. Naming conventions. 43

Known Uses Factory methods pervade toolkits and frameworks. Class View in the Smalltalk-8 0Model/View/Controller framework has a method default Controller that creates a controller, and this might appear to be a factory method. The Orbix ORB system from IONA Technologies uses Factory Method to generate an appropriate type of proxy when an object requests a reference to a remote object. 44

Related Patterns Abstract Factory is often implemented with factory methods. The Motivation example in the Abstract Factory pattern illustrates Factory Method as well. Factory methods are usually called within Template Methods. In the document example above, NewDocument is a template method. 45

46

Related Patterns 47

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

PROTOTYPE (Object Creational) Intent: ospecify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. Motivation: oframework implements Graphic class for graphical components and GraphicTool class for tools manipulating/creating those components 65

Motivation Actual graphical components are application-specific How to parameterize instances of Graphic Tool class with type of objects to create? Solution: create new objects in Graphic Tool by cloning a prototype object instance 66

PROTOTYPE Motivation Tool Manipulate() prototype Graphic Draw(Position) Clone() Staff MusicalNote Rotate Tool Manipulate() Graphic Tool Manipulate() Draw(Position) Clone() p = prototype ->Clone() while(user drags mouse){ p ->Draw(new position) } Insert p into drawing WholeNote Draw(Position) Clone() Return copy of self HalfNote Draw(Position) Clone() Return copy of self 67

PROTOTYPE Motivation Usage: Easy pattern, usage depends on the preferred software design, provides an alternative to the other creational patterns that are mainly based on external classes for creation 68

Applicability Use the Prototype pattern when a system should be independent of how its products are created, composed, and represented; owhen the classes to instantiate are specified at runtime, for example, by dynamic loading; or oto avoid building a class hierarchy of factories that parallels the class hierarchy of products; or 69

Applicability when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state. 70

PROTOTYPE Structure client prototype Prototype Operation() Clone() p = prototype ->Clone() ConcretePrototype1 Clone() ConcretePrototype2 Clone() return copy of self return copy of self 71

Participants: Prototype (Graphic) odeclares an interface for cloning itself ConcretePrototype (Staff, WholeNote, HalfNote) oimplements an interface for cloning itself Client (GraphicTool) ocreates a new object by asking a prototype to clone itself L5 Collaborations: A client asks a prototype to clone Itself. UNIT-III 72

Consequences Adding and removing products at run-time. Specifying new objects by varying values. Specifying new objects by varying structure. Reduced subclassing. Configuring an application with classes dynamically. 73

Implementation Using a prototype manager. Implementing the Clone operation. Initializing clones. 74

Known Uses first example of the Prototype pattern was in Ivan Sutherland's Sketchpad system first widely known application of the pattern in an object oriented language was in ThingLab, where users could form a composite object and then promote it to a prototype by installing it in a library of reusable objects 75

Related Patterns Prototype and Abstract Factory are competing patterns in some ways, as we discuss at the end of this chapter. They can also be used together, however. An Abstract Factory might store a set of prototypes from which to clone and return product objects. Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well. 76

77

79

80

abstract class ColorPrototype { public abstract ColorPrototype Clone(); } ------------------------------ class Color:ColorPrototype { public int Red; public int Green; public int Blue; public override ColorPrototype Clone() { return this.memberwiseclone() as ColorPrototype; } } 81

private void button1_click(object sender, EventArgs e) { Color c1 = new Color(); c1.green = 255; Color c2 = c1.clone() as Color; } 82

Intent: SINGELTON oensure a class only has one instance, and provide a global point of access to it. Motivation: osome classes should have exactly one instance (one print spooler, one file system, one window manager) oa global variable makes an object accessible but doesn t prohibit instantiation of multiple objects oclass should be responsible for keeping track of its sole interface 83

SINGELTON Usage: Often used for objects that need to provide global access with the constraint of only one single instance in the application 84

Applicability Use the Singleton pattern when othere must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. owhen the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code. 85

SINGLETON Structure Singleton static Instance() return uniquelnstance SingletonOperation() GetSingletonData() Static uniquelnstance singletondata 86

Singleton: Participants and Collaborations Defines an instance operation that lets clients access its unique interface Instance is a class operation (static in Java) May be responsible for creating its own unique instance Collaborations: Clients access a Singleton instance solely through Singleton s Instance operation. 87

Consequences Controlled access to sole instance. Reduced name space. Permits refinement of operations and representation. Permits a variable number of instances. More flexible than class 88

Implementation Points Generally, a single instance is held by the object, and controlled by a single interface. Sub classing the Singleton may provide both default and overridden functionality. 89

Known Uses A more subtle example is the relationship between classes and their metaclasses. A metaclass is the class of a class, and each metaclass has one instance. Metaclasses do not have names (except indirectly through their sole instance), but they keep track of their sole instance and will not normally create another. 90

Related pattern Many patterns can be implemented using the Singleton pattern. See Abstract Factory, Builder, and Prototype. 91

Discussion of Creational Patterns There are two common ways to parameterize a system by the classes of objects it creates: One way is to subclass the class that creates the objects The other way to parameterize a system relies more on object composition 94

Discussion of Creational Patterns Which pattern is best depends on many factors. Abstract Factory doesn't offer much of an improvement, because it requires an equally large Graphics Factory class hierarchy. the Prototype pattern is probably the best for the drawing editor framework, because it only requires implementing a Clone operation on each Graphics class. Factory Method makes a design more customizable and only a little more complicated. 97

Discussion of Creational Patterns Designs that use Abstract Factory, Prototype, or Builder are even more flexible than those that use Factory Method, but they're also more complex. Often, designs start out using Factory Method and evolve toward the other creational patterns as the designer discovers where more flexibility is needed. 98