Design Patterns David Talby. 11/20/2016Object Oriented Design Course2 Contents Representing Data Structures Composite Flyweight Decorator Traversing Data.

Slides:



Advertisements
Similar presentations
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Advertisements

Chapter 14 Graph class design John Keyser’s Modifications of Slides by Bjarne Stroustrup
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Design Patterns David Talby. This Lecture n More for a Document Editor u Synchronizing Multiple Windows F Observer u Simplifying complex interactions.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
Design Patterns David Talby. This Lecture Representing other objects Proxy, Adapter, Façade Re-routing method calls Chain of Responsibility Coding partial.
GoF Sections 2.7 – 2.9 More Fun with Lexi. Lexi Document Editor Lexi tasks discussed:  Document structure  Formatting  Embellishing the user interface.
C15: Design Patterns Gamma,Helm,Johnson,Vlissides (GOF)
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Design Patterns David Talby. This Lecture n Representing Data Structures u Composite, Flyweight, Decorator n Traversing Data Structures u Iterator, Visitor.
Design Patterns David Talby. This Lecture n Patterns for a User Interface u Representing a Document F Composite, Flyweight, Decorator u Writing Portable.
Design Patterns David Talby. This Lecture n The Creational Patterns u Builder u Prototype u Factory Method u (Abstract Factory) u Singleton n Choosing.
Design Patterns. CS351 - Software Engineering (AY2007)Slide 2 Behavioral patterns Suppose we have an aggregate data structure and we wish to access the.
Trees. Definition of a tree A tree is like a binary tree, except that a node may have any number of children –Depending on the needs of the program, the.
Design Patterns David Talby. This Lecture Handle Synchronization & Events Observer Simplify Complex Interactions Mediator Change Behavior Dynamically.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
GoF Sections 2.7 – 2.9 More Fun with Lexi. Lexi Document Editor Lexi tasks discussed:  Document structure  Formatting  Embellishing the user interface.
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.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
C++ fundamentals.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Starting Chapter 4 Starting. 1 Course Outline* Covered in first half until Dr. Li takes over. JAVA and OO: Review what is Object Oriented Programming.
Design Dan Fleck CS 421 George Mason University. What is the design phase? Analysis phase describes what the system should do Analysis has provided a.
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.
Lexi case study (Part 2) Presentation by Matt Deckard.
Decorator Explained. Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
GoF: Document Editor Example Rebecca Miller-Webster.
Can’t provide fast insertion/removal and fast lookup at the same time Vectors, Linked Lists, Stack, Queues, Deques 4 Data Structures - CSCI 102 Copyright.
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.
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
Structural Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
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.
CS212: Object Oriented Analysis and Design Lecture 39: Design Pattern-III.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Examples (D. Schmidt et al)
Patterns in programming
1/23/2018 Design Patterns David Talby.
Mr. Marino – 6th Grade Computer Applications
4/16/2018 Design Patterns David Talby.
Chapter 0: Introduction
Topic 2: binary Trees COMP2003J: Data Structures and Algorithms 2
Design Patterns: MORE Examples
UofC Large Display Framework
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University
MIS 215 Module 1 – Unordered Lists
Software Design and Architecture
Word Processing.
Chapter 17 Object-Oriented Data Structures
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Object Oriented Programming (OOP) LAB # 8
Design Patterns A Case Study: Designing a Document Editor
Jim Fawcett CSE776 – Design Patterns Summer 2003
Linked Lists.
Advanced Implementation of Tables
Introduction to Data Structure
Data Structures & Algorithms
Object Oriented Design
CS2013 Lecture 7 John Hurley Cal State LA.
CMPE212 – Reminders Quiz 1 marking done. Assignment 2 due next Friday.
CMPE212 – Reminders Assignment 2 due next Friday.
Java String Class String is a class
Presentation transcript:

Design Patterns David Talby

11/20/2016Object Oriented Design Course2 Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor

11/20/2016Object Oriented Design Course3 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

11/20/2016Object Oriented Design Course4 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).

11/20/2016Object Oriented Design Course5 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

11/20/2016Object Oriented Design Course6 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.)

11/20/2016Object Oriented Design Course7 The Solution II This new class inherits it as well: class CompositeGraphic : public Graphic, public list { void rotate(double angle) { for (int i=0; i<count(); i++) item(i)->rotate(angle); }

11/20/2016Object Oriented Design Course8 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

11/20/2016Object Oriented Design Course9 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

11/20/2016Object Oriented Design Course10 The GoF UML Single Inheritance Root has add(), remove() methods

11/20/2016Object Oriented Design Course11 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.)

11/20/2016Object Oriented Design Course12 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

11/20/2016Object Oriented Design Course13 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

11/20/2016Object Oriented Design Course14 Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor

11/20/2016Object Oriented Design Course15 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...

11/20/2016Object Oriented Design Course16 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; }

11/20/2016Object Oriented Design Course17 Composite Documents

11/20/2016Object Oriented Design Course18 At Runtime Unlimited Hierarchy problem solved Dynamic selection of composites Open for additions

11/20/2016Object Oriented Design Course19 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?

11/20/2016Object Oriented Design Course20 The Requirements Reduce the memory demands of having an object per character Keep the flexibility to customize each character differently

11/20/2016Object Oriented Design Course21 The Solution Intrinsic state = worth sharing Extrinsic state = not worth sharing

11/20/2016Object Oriented Design Course22 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 }

11/20/2016Object Oriented Design Course23 The Solution III Original class holds rest of state: class Character : public Glyph { CharacterContext *cc; int x, y; draw() { cc->draw(x,y); }

11/20/2016Object Oriented Design Course24 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, …); }

11/20/2016Object Oriented Design Course25 The UML

11/20/2016Object Oriented Design Course26 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

11/20/2016Object Oriented Design Course27 Known Uses Word processors Average 1 flyweight per 400 letters Widgets All data except location, value Strategy design pattern State design pattern

11/20/2016Object Oriented Design Course28 Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor

11/20/2016Object Oriented Design Course29 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, …

11/20/2016Object Oriented Design Course30 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

11/20/2016Object Oriented Design Course31 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; }

11/20/2016Object Oriented Design Course32 The Solution II Define concrete decorators: class BackgroundDecorator : public Decorator { void draw() { drawBackground(); glyph->draw(); }

11/20/2016Object Oriented Design Course33 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

11/20/2016Object Oriented Design Course34 The UML

11/20/2016Object Oriented Design Course35 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

11/20/2016Object Oriented Design Course36 Known Uses Embellishing Document Background, Border, Note,... Communication Streams Encrypted, Buffered, Compressed

11/20/2016Object Oriented Design Course37 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

11/20/2016Object Oriented Design Course38 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

11/20/2016Object Oriented Design Course39 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!

11/20/2016Object Oriented Design Course40 Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor

11/20/2016Object Oriented Design Course41 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

11/20/2016Object Oriented Design Course42 The Requirements Traversal operations should be separate from List ’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

11/20/2016Object Oriented Design Course43 The Solution Define an abstract iterator class: class Iterator { void first() = 0; void next() = 0; bool isDone() = 0; G* item() = 0; }

11/20/2016Object Oriented Design Course44 The Solution II Each data structure implementation will also implement an iterator class: ListIterator HashTableIterator FileIterator StringIterator Each data structure can offer more than one iterator: Forward and backward iterators Preorder, inorder, postorder

11/20/2016Object Oriented Design Course45 The Solution III For example: class BackwardArrayIterator : public Iterator { Array *container; int pos; public: BackwardArrayIterator(Array *a) { container = a; first(); } next() { --pos; } // other methods easy }

11/20/2016Object Oriented Design Course46 The Solution IV A data structure’s interface should return iterators on itself: class List { Iterator * getForwardIterator() { return new ListForwardIterator(this); } Iterator * getBackwardIterator() // similarly } Now every LinkedList object can have many active iterators

11/20/2016Object Oriented Design Course47 The Solution V Writing functions for containers: void print(Iterator * it) { for (it->first(); !it->isDone(); it->next()) cout item(); } Using them: print(myList->getBackwardIterator()); print(myTable->getColumnItr(“Age”)); print(myTree->getPostOrderIterator());

11/20/2016Object Oriented Design Course48 The Solution VI Generic algorithms can be written: G* findItem(Iterator * it, G *element) { while (!it->isDone()) { if (it->item() == element) return element; it->next(); } return NULL; }

11/20/2016Object Oriented Design Course49 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

11/20/2016Object Oriented Design Course50 The Solution Use the Decorator design pattern For example, FilteredIterator 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()); }

11/20/2016Object Oriented Design Course51 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

11/20/2016Object Oriented Design Course52 The UML

11/20/2016Object Oriented Design Course53 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

11/20/2016Object Oriented Design Course54 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

11/20/2016Object Oriented Design Course55 Known Uses All major standard libraries of popular programming languages STL for C++ The Java Collections Framework New libraries for file, network and database access in C++ conform to STL’s iterators as well

11/20/2016Object Oriented Design Course56 Contents Representing Data Structures Composite Flyweight Decorator Traversing Data Structures Iterator Visitor

11/20/2016Object Oriented Design Course57 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, auto-format, … How do we avoid cluttering Glyph subclasses with all this code?

11/20/2016Object Oriented Design Course58 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

11/20/2016Object Oriented Design Course59 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

11/20/2016Object Oriented Design Course60 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

11/20/2016Object Oriented Design Course61 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

11/20/2016Object Oriented Design Course62 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

11/20/2016Object Oriented Design Course63 The UML

11/20/2016Object Oriented Design Course64 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

11/20/2016Object Oriented Design Course65 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

11/20/2016Object Oriented Design Course66 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!