Design Patterns David Talby. This Lecture n Patterns for a User Interface u Representing a Document F Composite, Flyweight, Decorator u Writing Portable.

Slides:



Advertisements
Similar presentations
1 CSIS 7102 Spring 2004 Lecture 9: Recovery (approaches) Dr. King-Ip Lin.
Advertisements

Chapter 14 Graph class design John Keyser’s Modifications of Slides by Bjarne Stroustrup
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.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
DESIGN PATTERNS OZGUR RAHMI DONMEZ.
Plab – Tirgul 12 Design Patterns
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 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.
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 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.
More OOP Design Patterns
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.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Behavioral Patterns  Behavioral patterns are patterns whose purpose is to facilitate the work of algorithmic calculations and communication between classes.
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.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
BLU-ICE and the Distributed Control System Constraints for Software Development Strategies Timothy M. McPhillips Stanford Synchrotron Radiation Laboratory.
Session 21 Chapter 10: Mechanisms for Software Reuse.
Lexi case study (Part 2) Presentation by Matt Deckard.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Object Oriented Software Engineering Chapter 16 and 17 review 2014/06/03.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
GoF: Document Editor Example Rebecca Miller-Webster.
CSE 403 Lecture 14 Design Patterns. Today’s educational objective Understand the basics of design patterns Be able to distinguish them from design approaches.
Structural Design Patterns
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.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns V More Structural Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
CDP-1 9. Creational Pattern. CDP-2 Creational Patterns Abstracts instantiation process Makes system independent of how its objects are –created –composed.
CSC 313 – Advanced Programming Topics. What Is the Factory Method?  Creation details hidden by AbstractCreator  Does effective job of limiting concrete.
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.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
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.
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
Advanced Object-oriented Design Patterns Creational Design Patterns.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
March 10, 2007 Design Patterns David Talby.
Design Patterns David Talby. 11/20/2016Object Oriented Design Course2 Contents Representing Data Structures Composite Flyweight Decorator Traversing Data.
1/23/2018 Design Patterns David Talby.
4/16/2018 Design Patterns David Talby.
Abstract Factory Pattern
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University
Software Design and Architecture
Lecture 27 Creating Custom GUIs
Abstract Factory Pattern
Intent (Thanks to Jim Fawcett for the slides)
Programming Design Patterns
Decorator Intent Also known as Wrapper Example: a Text Window
Design Patterns A Case Study: Designing a Document Editor
Behavioral and Structural Patterns
Object Oriented Design
Presentation transcript:

Design Patterns David Talby

This Lecture n Patterns for a User Interface u Representing a Document F Composite, Flyweight, Decorator u Writing Portable Code F Abstract Factory, Singleton, Bridge u Undo, Macros and Versions F Command

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

A Data Structure n 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; }

Composite Documents

At Runtime n Unlimited Hierarchy problem solved n Dynamic selection of composites n Open for additions

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

The Requirements n Reduce the memory demands of having an object per character n Keep the flexibility to customize each character differently

The Solution n Extrinsic state = worth sharing n Intrinsic state = not worth sharing

The Solution II n Put extrinsic 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 }

The Solution III n Original class holds rest of state: class Character : public Glyph { CharacterContext *cc; int x, y; draw() { cc->draw(x,y); }

The Solution IV n A factory manages the shared pool n It adds the object to the pool if it doesn’t exists, and returns it n Here’s Character ’s constructor: Character(int x, int y, Font *f, …) { this->x = x; this->y = y; this->cc = factory.createCharacter(f, …); }

The UML

The Fine Print n There’s a lot of tradeoff in what is defined as “extrinsic” n Shared pool is usually a hash table n Use reference counting to collect unused flyweights n Don’t rely on object identity u Different objects will seem equal

Known Uses n Word processors u Average 1 flyweight per 400 letters n Widgets u All data except location, value n Strategy design pattern n State design pattern

9. Decorator n Attach additional features to an objects dynamically n For example, many features can be added to any glyph in a document u Background, Note, Hyperlink, Shading, Borders, …

The Requirements n We can freely combine features u An image can have a background, a border, a hyper-link and a note n Features are added and removed dynamically n Can’t afford a class per combination n Should be easy to add new features u Don’t put it all in Glyph

The Solution n 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; }

The Solution II n Define concrete decorators: class BackgroundDecorator : public Decorator { void draw() { drawBackground(); glyph->draw(); }

The Solution III n Many decorators can be added and removed dynamically: n Behavior can be added before and after calling the component n Efficient in space n Order of decoration can matter

The UML

The Fine Print n The Decorator class can be omitted if there’s only one decorator or Glyph is very simple n The Glyph class should be lightweight and not store data

Known Uses n Embellishing Document u Background, Border, Note,... n Communication Streams u Encrypted, Buffered, Compressed

Data Structure Summary n Patterns work nicely together u Composite, Decorator, Flyweight don’t interfere n Data structures are not layered u Instead, clients work on a Glyph interface hiding structures of unknown, dynamic complexity

Saving and Loading n Java has serialization n Save to disk / Send over network by simply writing the root Glyph object of a document n All optimizations saved as well! n Also works on subtrees n Very little coding n In C++ - best to code read() and write() and work the same way

Cut, Copy, Paste n Cut = Detach a subtree n Copy = Clone a subtree n Paste = Attach a subtree n Also works on composite glyphs n Glyphs should hold a reference to parents for the cut operations n Cloning of a flyweight should only increase its reference count!

10. Bridge n Separate an abstraction from its implementations n For example, a program must run on several platforms n Each platform comes with its own set of GUI classes: WinButton, WinScrollBar, WinWindow MotifButton, MotifScrollBar, MotifWindow pmButton, pmScrollBar, pmWindow

Abstract Factory, Right? n An abstract factory can be used to provide these advantages: u Clients treat widgets uniformly u Easy to add or switch families n However, it requires a class per platform per abstraction:

The Requirements n One class per abstraction, one class per implementation u Basically all platforms give similar functionality for a window u If a platform doesn’t support a feature, we should code it once

The Solution Separate the two hierarchies:

The Solution II n Usually, an implementation inherits the abstraction it implements n The Bridge patterns simply replaces this by composition n This gives several advantages in cases such as the above: u An abstraction can choose its implementation at runtime u Even change implementations

The Solution III u Both the abstractions and the implementations can be extended by subclassing u Changing one does not force recompilation of the other u In C++ this technique completely hides a class’s implementation (its private functions and members) u Many abstractions can share the same implementation

The GoF UML

The Fine Print n Choosing the implementor can still be done with an Abstract Factory n Stateless implementors can be shared (so the Abstract Factory becomes a Flyweight factory)

Known Uses n A program that must run on several platforms n A data structures library u Abstractions: Set, List, Array, Table u Implementations: LinkedList, HashTable, DenseArray, … n Different kinds of images versus algorithms to display them

11. Command n Encapsulate commands as objects n We’ll take the the uses one by one: u Undo/Redo u Macros u Queues and logs u Version control u Crash recovery u Message Grouping

The Requirements I n Undo / redo at unlimited depth n Only store relevant data for undo n Easy to add commands

The Solution n Repesent a command as a class: class Command { public: virtual void execute() = 0; virtual void undo() = 0; }

The Solution II n Concrete commands hold undo data: class DeleteLine : public Command { void execute() { line = document->getLine(); document->removeLine(); } void undo() { document->addLine(line); } private: Line line; }

The Solution III n Keep a list of executed commands: Array commands; int i; n When you click the ‘Undo’ button: commands(i)->undo(); i--; n When you click the ‘Redo’ button: commands(i)->execute(); i++;

The Solution IV n Whenever a command is activated: commands.add(new_command); i = commands.count(); n When you save a document: document->save(); commands.clear(); i = 0; n The commands list may or may not be limited in size n Only relevant undo data is kept

The Requirements II n Macros are a series of commands n Any command with any of its options may be used n There are also for and while loops, if statements, calls to other macros...

The Solution n A macro is a Composite Command n if, for, while are Decorator Commands

The Requirements III n Commands are accessible from menus as well as toolbars n A command may be available from more than one place n We’d like to configure the menus and toolbars at runtime

The Solution n Each MenuItem or ToolbarItem refers to its command object n Just as it refers to an image n The command can be configured u Less command classes n Macros fit in the picture as well!

The Requirements IV n Keep multiple versions of a document n When saving, only store the changes from the previous version

The Solution n The changes are exactly the list of commands since the last version was loaded n In addition, a compaction algorithm is needed for commands that cancel each other n Save = Serialize the compacted list n Load = Read early version and call execute on command lists

(More!) Known Uses n Programs log commands to disk so they can be used in case of a crash u Works, since commands are small u Usually in a background thread n Commands can be grouped and sent as one command to a server u Grouping for efficient communication u Grouping to define a transaction u Works even for user defined macros!

Another Summary n Interfaces rule u As long as Command is abstract, who cares how complex it is n Composition rules u Decorator and Bridge provide flexibility in less written code by avoiding inheritance n Serialization should rule