Design Patterns. David Talby

Similar documents
David Talby March 21, 2006

Design Patterns in C++

Last Lecture. Lecture 26: Design Patterns (part 2) State. Goals of Lecture. Design Patterns

Last Lecture. Lecture 17: Design Patterns (part 2) Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 4448/ Spring Semester, 2005

Think of drawing/diagramming editors. ECE450 Software Engineering II. The problem. The Composite pattern

Composite Pattern. IV.4 Structural Pattern

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

Design Patterns. Comp2110 Software Design. Department of Computer Science Australian National University. Second Semester

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?

Design Patterns IV. Alexei Khorev. 1 Structural Patterns. Structural Patterns. 2 Adapter Design Patterns IV. Alexei Khorev. Structural Patterns

Design Patterns IV Structural Design Patterns, 1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1

Design Pattern and Software Architecture: IV. Design Pattern

CSE 401/M501 Compilers

SDC Design patterns GoF

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

Compositional Model Based Software Development

Design Patterns. Lecture 10: OOP, autumn 2003

What are patterns? Design Patterns. Design patterns. Creational patterns. The factory pattern. Factory pattern structure. Lecture 10: OOP, autumn 2003

CSE 70 Final Exam Fall 2009

Introduction to Design Patterns

Java Object Oriented Design. CSC207 Fall 2014

The GoF Design Patterns Reference

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Design Patterns V Structural Design Patterns, 2

DESIGN PATTERN - INTERVIEW QUESTIONS

P2: Collaborations. CSE 335, Spring 2009

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

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

CMSC 341 Lecture 10 Binary Search Trees

Overview CS Kinds of Patterns. Design Pattern. Factory Pattern Rationale. Kinds of Factory Patterns

The Object Recursion Pattern

Object-Oriented Oriented Programming

Design Patterns. Decorator. Oliver Haase

Object-oriented Compiler Construction

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

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

1. Stack overflow & underflow 2. Implementation: partially filled array & linked list 3. Applications: reverse string, backtracking

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

COURSE 2 DESIGN PATTERNS

COSC 3351 Software Design. Design Patterns Structural Patterns (II) Edgar Gabriel. Spring Decorator

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

A Case Study of Gang of Four (GoF) Patterns : Part 7

Design Pattern: Composite

Inheritance, and Polymorphism.

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

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

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

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

Chapter 20: Binary Trees

CIS 121 Data Structures and Algorithms with Java Spring 2018

ECE 3574: Dynamic Polymorphism using Inheritance

OO Overkill When Simple is Better than Not

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

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

EINDHOVEN UNIVERSITY OF TECHNOLOGY

Friday Four Square! 4:15PM, Outside Gates

The Composite Pattern

Design Patterns. (and anti-patterns)

Trees and Tree Traversals. Binary Trees. COMP 210: Object-Oriented Programming Lecture Notes 8. Based on notes by Logan Mayfield

Project 1: Scheme Pretty-Printer

Object- Oriented Design with UML and Java Part I: Fundamentals

OO Overkill When Simple is Better than Not

The Design Patterns Matrix From Analysis to Implementation

Chapter 6 Introduction to Defining Classes

1: Introduction to Object (1)

CS 2720 Practical Software Development University of Lethbridge. Design Patterns

Top Down Design vs. Modularization

Tuesday, October 4. Announcements

2.1 Design Patterns and Architecture (continued)

COURSE 4 DESIGN PATTERNS

2.1 Design Patterns and Architecture (continued)

1B1b Classes in Java Part I

Binary Tree Node Relationships. Binary Trees. Quick Application: Expression Trees. Traversals

Binary Trees. For example: Jargon: General Binary Trees. root node. level: internal node. edge. leaf node. Data Structures & File Management

Software Eningeering. Lecture 9 Design Patterns 2

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

C++ Inheritance and Encapsulation

Design Patterns Lecture 2

Topics in Object-Oriented Design Patterns

Introduction to Software Engineering: Object Design I Reuse & Patterns

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

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

Design Patterns Reid Holmes

Cmpt 135 Assignment 2: Solutions and Marking Rubric Feb 22 nd 2016 Due: Mar 4th 11:59pm

Using Design Patterns in Java Application Development

» Access elements of a container sequentially without exposing the underlying representation

Fast Introduction to Object Oriented Programming and C++

Review sheet for Final Exam (List of objectives for this course)

Multiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence:

COEN244: Class & function templates

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

The Composite Design Pattern

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

Programming II (CS300)

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CS 370 Design Heuristics D R. M I C H A E L J. R E A L E F A L L

Organization of User Interface Software

Transcription:

Design Patterns David Talby

Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor May 27, 2008 Object Oriented Design Course 2

Design Patterns Reminder Documented Proved Design Experience Finding the right classes Finding them faster Common design jargon Consistent format Coded infrastructures Criteria for Success Open-Closed Principle Single Choice Principle May 27, 2008 Object Oriented Design Course 3

1. Composite A program must treat simple and complex objects uniformly For example, a painting program has simple objects (lines, circles and texts) as well as composite ones (wheel = circle + six lines). May 27, 2008 Object Oriented Design Course 4

The Requirements Treat simple and complex objects uniformly in code - move, erase, rotate and set color work on all Some composite objects are defined statically (wheels), while others dynamically (user selection) Composite objects can be made of other composite objects We need a smart data structure May 27, 2008 Object Oriented Design Course 5

The Solution All simple objects inherit from a common interface, say Graphic: class Graphic { void move(int x, int y) = 0; void setcolor(color c) = 0; void rotate(double angle) = 0; } The classes Line, Circle and others inherit Graphic and add specific features (radius, length, etc.) May 27, 2008 Object Oriented Design Course 6

The Solution II This new class inherits it as well: class CompositeGraphic : public Graphic, public list<graphic> { void rotate(double angle) { for (int i=0; i<count(); i++) item(i)->rotate(angle); } } May 27, 2008 Object Oriented Design Course 7

The Solution III Since a CompositeGraphic is a list, it had add(), remove() and count() methods Since it is also a Graphic, it has rotate(), move() and setcolor() too Such operations on a composite object work using a forall loop Works even when a composite holds other composites - results in a tree-like data structure May 27, 2008 Object Oriented Design Course 8

The Solution IV Example of creating a composite: CompositeGraphic *cg; cg = new CompositeGraphic(); cg->add(new Line(0,0,100,100)); cg->add(new Circle(50,50,100)); cg->add(t); // dynamic text graphic cg->remove(2); Can keep order of inserted items if the program needs it May 27, 2008 Object Oriented Design Course 9

The GoF UML Single Inheritance Root has add(), remove() methods May 27, 2008 Object Oriented Design Course 10

The Fine Print Sometimes useful to let objects hold a pointer to their parent A composite may cache data about its children (count is an example) Make composites responsible for deleting their children Beware of circles in the graph! Any data structure to hold children will do (list, array, hashtable, etc.) May 27, 2008 Object Oriented Design Course 11

Known Uses In almost all O-O systems Document editing programs GUI (a form is a composite widget) Compiler parse trees (a function is composed of simpler statements or function calls, same for modules) Financial assets can be simple (stocks, options) or a composite portfolio May 27, 2008 Object Oriented Design Course 12

Pattern of Patterns Encapsulate the varying aspect Interfaces Inheritance describes variants Composition allows a dynamic choice between variants Criteria for success: Open-Closed Principle Single Choice Principle May 27, 2008 Object Oriented Design Course 13

Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor May 27, 2008 Object Oriented Design Course 14

A Word Processor Pages, Columns, Lines, Letters, Symbols, Tables, Images,... Font and style settings per letter Frames, Shadows, Background, Hyperlink attached to anything Unlimited hierarchy: Tables with several Paragraphs containing hyper-linked images inside tables Should be open for additions... May 27, 2008 Object Oriented Design Course 15

A Data Structure First, a uniform interface for simple things that live in a document: class Glyph { void draw(window *w) = 0; void move(double x, double y) = 0; bool intersects(point *p) = 0; } void insert(glyph *g, int i) = 0; void remove(int i) = 0; Glyph* child(int i) = 0; Glyph* parent() = 0; May 27, 2008 Object Oriented Design Course 16

Composite Documents May 27, 2008 Object Oriented Design Course 17

At Runtime Unlimited Hierarchy problem solved Dynamic selection of composites Open for additions May 27, 2008 Object Oriented Design Course 18

2. Flyweight Use sharing to support a large number of small objects efficiently For example, if every character holds font and style data, a long letter will require huge memory Even though most letters use the same font and style How do we make it practical to keep each character as an object? May 27, 2008 Object Oriented Design Course 19

The Requirements Reduce the memory demands of having an object per character Keep the flexibility to customize each character differently May 27, 2008 Object Oriented Design Course 20

The Solution Intrinsic state = worth sharing Extrinsic state = not worth sharing May 27, 2008 Object Oriented Design Course 21

The Solution II Put intrinsic state in a class: class CharacterContext { Font* font; bool isitalic, isbold,...; int size; int asciicode; // many others } draw(int x, int y) {... } // other operational methods May 27, 2008 Object Oriented Design Course 22

The Solution III Original class holds rest of state: class Character : public Glyph { CharacterContext *cc; int x, y; } draw() { cc->draw(x,y); } May 27, 2008 Object Oriented Design Course 23

The Solution IV A factory manages the shared pool It adds the object to the pool if it doesn t exists, and returns it Here s Character s constructor: Character(int x, int y, Font *f, ) { this->x = x; this->y = y; this->cc = factory.createcharacter(f, ); } May 27, 2008 Object Oriented Design Course 24

The UML May 27, 2008 Object Oriented Design Course 25

The Fine Print There s a lot of tradeoff in what is defined as extrinsic Shared pool is usually a hash table Use reference counting to collect unused flyweights Don t rely on object identity Different objects will seem equal May 27, 2008 Object Oriented Design Course 26

Known Uses Word processors Average 1 flyweight per 400 letters Widgets All data except location, value Strategy design pattern State design pattern May 27, 2008 Object Oriented Design Course 27

Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor May 27, 2008 Object Oriented Design Course 28

3. Decorator Attach additional features to an object dynamically For example, many features can be added to any glyph in a document Background, Note, Hyperlink, Shading, Borders, May 27, 2008 Object Oriented Design Course 29

The Requirements We can freely combine features An image can have a background, a border, a hyper-link and a note Features are added and removed dynamically Can t afford a class per combination Should be easy to add new features Don t put it all in Glyph May 27, 2008 Object Oriented Design Course 30

The Solution Meet Decorator, a class for adding responsibilities to another glyph: class Decorator : public Glyph { void draw() { component->draw(); } // same for other features private: Glyph *component; } May 27, 2008 Object Oriented Design Course 31

The Solution II Define concrete decorators: class BackgroundDecorator : public Decorator { void draw() { drawbackground(); glyph->draw(); } } May 27, 2008 Object Oriented Design Course 32

The Solution III Many decorators can be added and removed dynamically: Behavior can be added before and after calling the component Efficient in space Order of decoration can matter May 27, 2008 Object Oriented Design Course 33

The UML May 27, 2008 Object Oriented Design Course 34

The Fine Print The Decorator class can be omitted if there s only one decorator or Glyph is very simple The Glyph class should be lightweight and not store data May 27, 2008 Object Oriented Design Course 35

Known Uses Embellishing Document Background, Border, Note,... Communication Streams Encrypted, Buffered, Compressed May 27, 2008 Object Oriented Design Course 36

Data Structure Summary Patterns work nicely together Composite, Decorator, Flyweight don t interfere Data structures are not layered Instead, clients work on a Glyph interface hiding structures of unknown, dynamic complexity May 27, 2008 Object Oriented Design Course 37

Saving and Loading Each Glyph should have deep read() and write() methods Save to disk / Send over network by simply writing the root Glyph object of a document All optimizations saved as well! Also works on subtrees Little coding May 27, 2008 Object Oriented Design Course 38

Cut, Copy, Paste Cut = Detach a subtree Copy = Clone a subtree Paste = Attach a subtree Also works on composite glyphs Glyphs should hold a reference to parents for the cut operations Cloning of a flyweight should only increase its reference count! May 27, 2008 Object Oriented Design Course 39

Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor May 27, 2008 Object Oriented Design Course 40

4. Iterator Traverse a data structure without exposing its representation An extremely common pattern For example, a list should support forward and backward traversals Certainly not by exposing its internal data structure Adding traversal methods to List s interface is a bad idea May 27, 2008 Object Oriented Design Course 41

The Requirements Traversal operations should be separate from List<G> s interface Allow several ongoing traversals on the same container Reuse: it should be possible to write algorithms such as finditem that work on any kind of list May 27, 2008 Object Oriented Design Course 42

The Solution Define an abstract iterator class: class Iterator<G> { void first() = 0; void next() = 0; bool isdone() = 0; G* item() = 0; } May 27, 2008 Object Oriented Design Course 43

The Solution II Each data structure implementation will also implement an iterator class: ListIterator<G> HashTableIterator<G> FileIterator<G> StringIterator<G> Each data structure can offer more than one iterator: Forward and backward iterators Preorder, inorder, postorder May 27, 2008 Object Oriented Design Course 44

The Solution III For example: class BackwardArrayIterator<G> : public Iterator<G> { Array<G> *container; int pos; public: BackwardArrayIterator(Array *a) { container = a; first(); } next() { --pos; } // other methods easy } May 27, 2008 Object Oriented Design Course 45

The Solution IV A data structure s interface should return iterators on itself: class List<G> { Iterator<G>* getforwarditerator() { return new ListForwardIterator(this); } Iterator<G>* getbackwarditerator() // similarly } Now every LinkedList object can have many active iterators May 27, 2008 Object Oriented Design Course 46

The Solution V Writing functions for containers: void print(iterator<int>* it) { for (it->first();!it->isdone(); it->next()) cout << it->item(); } Using them: print(mylist->getbackwarditerator()); print(mytable->getcolumnitr( Age )); print(mytree->getpostorderiterator()); May 27, 2008 Object Oriented Design Course 47

The Solution VI Generic algorithms can be written: G* finditem(iterator<g>* it, G *element) { while (!it->isdone()) { if (it->item() == element) return element; it->next(); } return NULL; } May 27, 2008 Object Oriented Design Course 48

The Requirements II Some iterators are generic: Traverse every n th item Traverse items that pass a filter Traverse only first n items Traverse a computed view of items Such iterators should be coded once It should be easy to combine such iterators and add new ones Their use should be transparent May 27, 2008 Object Oriented Design Course 49

The Solution Use the Decorator design pattern For example, FilteredIterator<G> receives another iterator and the filtering function in its constructor It delegates all calls to its internal iterator except first() and next(): void next() { do it->next() while (!filter(it->item() &&!it->isdone()); } May 27, 2008 Object Oriented Design Course 50

The Solution II It is then easy to combine such generic iterators Print square roots of the first 100 positive elements in a list: print(new LimitedIterator(100, new ComputedIterator(sqrt, new FilteredIterator(positive, list->getforwarditerator())))); Adding an abstract DecoratorIterator reduces code size if many exist May 27, 2008 Object Oriented Design Course 51

The UML May 27, 2008 Object Oriented Design Course 52

The Fine Print Everything is a container Character strings Files, both text and records Socket streams over the net The result of a database query The bits of an integer Stream of random or prime numbers This allows reusing the print, find and other algorithms for all of these May 27, 2008 Object Oriented Design Course 53

The Fine Print II Iterators may have privileged access They can encapsulate security rights Kinds of abstract iterators Direct access iterators Access the previous item Robustness issues Is the iterator valid after insertions or removals from the container? Iterators and the Composite pattern May 27, 2008 Object Oriented Design Course 54

Known Uses All major standard libraries of popular programming languages STL for C++ The Java Collections Framework.net System.Collection namespace New libraries for file, network and database access in C++ conform to STL s iterators as well May 27, 2008 Object Oriented Design Course 55

Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor May 27, 2008 Object Oriented Design Course 56

5. Visitor Separate complex algorithms on a complex data structure from the structure s representation For example, a document is a composite structure involved in many complex operations Spell check, grammar check, hyphenation, autoformat, How do we avoid cluttering Glyph subclasses with all this code? May 27, 2008 Object Oriented Design Course 57

The Requirements Encapsulate complex algorithms and their data in one place Outside the data structure Easily support different behavior for every kind of Glyph Easily add new tools May 27, 2008 Object Oriented Design Course 58

The Solution Say hello to class Visitor: class Visitor { public: void visitimage(image *i) { } void visitrow(row *r) { } void visittable(table *t) { } // so on for every Glyph type } Every tool is a subclass: class SpellChecker : public Visitor May 27, 2008 Object Oriented Design Course 59

The Solution II Add to Glyph s interface the ability to accept visitors: void accept(visitor *v) = 0; Every glyph subclass accepts a visitor by an appropriate callback: class Image : public Glyph { void accept(visitor *v) { v->visitimage(this); } This way the visitor is activated for the right kind of glyph, with its data May 27, 2008 Object Oriented Design Course 60

The Solution III Initiating a spell check (one option): Create a SpellChecker object root->accept(sc); Graphic non-text glyphs will just ignore the visit This is why Visitor includes default empty method implementations Composite glyphs also do nothing They can forward the visit to children. This can be coded once in CompositeGlyph May 27, 2008 Object Oriented Design Course 61

The Solution IV Easy to add operations Word count on characters Filters such as sharpen on images Page layout changes on pages Works on any glyph In particular, a dynamic selection as long as it s a composite glyph Adding a tool does not require recompilation of Glyph hierarchy May 27, 2008 Object Oriented Design Course 62

The UML May 27, 2008 Object Oriented Design Course 63

The Fine Print The big problem: adding new Glyph subclasses is hard Requires small addition to Visitor, and recompilation of all its subclasses How do we traverse the structure? Using an iterator From inside the accept() code From inside the visitxxx() code Visitors are really just a workaround due to the lack of double dispatch May 27, 2008 Object Oriented Design Course 64

The fine print (II) How to return a value from a visitor? Visitor v = new Visitor(); element.accept(v); Object o = v.getresult(); May 27, 2008 Object Oriented Design Course 65

Known Uses Document Editors Spell Check, Auto-Format, Photo Editors Filters & Effects Compilers Code production, pretty printing, tests, metrics and optimizations on the syntax tree May 27, 2008 Object Oriented Design Course 66

Visitor Example No Composite involved Real working application WorldMate Live Manages Itineraries Each itinerary contains a list of itinerary items May 27, 2008 Object Oriented Design Course 67

The UML May 27, 2008 Object Oriented Design Course 68

Implements algorithms Add/remove items Event creator Converters Default values setter etc. May 27, 2008 Object Oriented Design Course 69

Summary Pattern of patterns Encapsulate the varying aspect Interfaces Inheritance describes variants Composition allows a dynamic choice between variants Design patterns are old, well known and thoroughly tested ideas Well over twenty years! May 27, 2008 Object Oriented Design Course 70