CSE 332: Design Patterns (Part I) Introduction to Design Patterns Design patterns were mentioned several times so far –And the Singleton Pattern was discussed.

Slides:



Advertisements
Similar presentations
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.
Advertisements

CS590L - Lecture 6 1 CS590L Distributed Component Architecture References: - E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design Patterns: Elements of.
GoF Sections 2.7 – 2.9 More Fun with Lexi. Lexi Document Editor Lexi tasks discussed:  Document structure  Formatting  Embellishing the user interface.
DESIGN PATTERNS OZGUR RAHMI DONMEZ.
More Interfaces, Dynamic Binding, and Polymorphism Kirk Scott.
Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
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.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Design Patterns.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
Powerpoint Templates Page 1 Powerpoint Templates What is Design Patterns ? by Indriati Teknik Informatika – UB.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 27. Review UML dynamic view – State Diagrams.
CSE 432: Design Patterns Introduction What’s a Pattern? What’s an Idiom? According to Alexander, a pattern: –Describes a recurring problem –Describes the.
Lexi case study (Part 2) Presentation by Matt Deckard.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
OBJECT-ORIENTED PROGRAMMING (OOP) WITH C++ Instructor: Dr. Hany H. Ammar Dept. of Electrical and Computer Engineering, WVU.
CSE 403 Lecture 14 Design Patterns. Today’s educational objective Understand the basics of design patterns Be able to distinguish them from design approaches.
CSE 432: Design Patterns Introduction What’s a Pattern? What’s an Idiom? According to Alexander, a pattern: –Describes a recurring problem –Describes the.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
ECE450S – Software Engineering II
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
CS212: Object Oriented Analysis and Design Lecture 37: Design Pattern.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Introduction to Object-Oriented Programming Lesson 2.
CSE 332: Design Patterns Introduction to Design Patterns You’ve seen design patterns several times this semester –The Iterator pattern has been discussed.
Overview of C++ Polymorphism
CSE 332: Design Patterns (Part II) Last Time: Part I, Familiar Design Patterns We’ve looked at patterns related to course material –Singleton: share a.
CSE 432: Thanks for the memory leaks, Pushme-Pullyu, and Command Summary of “Thanks for the Memory Leaks” “Left-over” design forces from Type Laundering.
Duke CPS Programming Heuristics l Identify the aspects of your application that vary and separate them from what stays the same ä Take what varies.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Design Patterns: MORE Examples
Introduction to Design Patterns
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Software Design Patterns
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Introduction to Design Patterns
Behavioral Design Patterns
object oriented Principles of software design
What’s a Design Pattern?
Software Engineering Lecture 7 - Design Patterns
Informatics 122 Software Design II
Review: Design Pattern Structure
Design Patterns Difficult to describe abstractly Elements:
Overview of C++ Polymorphism
Informatics 122 Software Design II
Presentation transcript:

CSE 332: Design Patterns (Part I) Introduction to Design Patterns Design patterns were mentioned several times so far –And the Singleton Pattern was discussed in detail –Along with several C++ memory management idioms The lectures this week will focus on them in detail –What they are and how they are structured –Introduction to the main “Gang of Four” design patterns The first set of design patterns should feel familiar –They use or help support C++ features we’ve discussed –We’ve seen examples of some of them already The second set is useful for advanced design topics –Different ways to set up how a group of objects interacts –How to send an object from one machine to another

CSE 332: Design Patterns (Part I) What’s a Pattern? What’s an Idiom? According to Alexander, a pattern: –Describes a recurring problem –Describes the core of a solution –Is capable of generating many distinct designs An Idiom is more restricted –Still describes a recurring problem –Provides a more specific solution, with fewer variations –Applies only to a narrow context e.g., the C++ language

CSE 332: Design Patterns (Part I) “Gang of Four” Pattern Structure Gang of Four (GoF): Gamma, Johnson, Helm, Vlissides –Authors of the popular “Design Patterns” book A pattern has a name –e.g., the Command pattern A pattern documents a recurring problem –e.g., Issuing requests to objects without knowing in advance what’s to be requested or of what object A pattern describes the core of a solution –e.g., class roles, relationships, and interactions –Important: this is different than describing a design A pattern considers consequences of its use –Trade-offs, unresolved forces, other patterns to use

CSE 332: Design Patterns (Part I) Simple Pattern Form Example: “Singleton” Problem –Want to ensure a single instance of a class, shared by all uses throughout a program Context –Need to address initialization versus usage ordering Solution –Provide a global access method (static in C++) –First use of the access method instantiates the class –Constructors for instance can be made private Consequences –Object is never created if it’s never used –Object is shared efficiently among all uses

CSE 332: Design Patterns (Part I) A More Complete Pattern Form: “Command” Problem –Want to issue requests to objects –Don’t know in advance which request(s) will be made –Don’t know in advance to what object(s) they will go Solution core –Encapsulate function call parameters and target object reference inside an “execute” method Consequences –Decouples invocation/execution –Commands are first-class objects (elevates functions) –Easy to compose, add new ones Example we’ve seen already –STL function objects

CSE 332: Design Patterns (Part I) Structure Diagram Example: “Command” Shows fixed class/interface roles in the pattern Shows fixed relationships between roles > action(args) execute ( ) state_ * client rolecommand role inheritance

CSE 332: Design Patterns (Part I) Collaboration Diagram Example: “Command” Shows dynamic interactions between pattern roles –Labels show what interaction does (here, labels show methods called) Often used to diagram each of several key scenarios –“Happy path” when everything works, plus different error cases aCommandanInvokeraClientaReceiver / construct store executeaction time

CSE 332: Design Patterns (Part I) Idiom Example: Guard Problem –Want to tie key scoped behaviors to actual program scopes e.g., program trace, resource acquisition/release, locking –However, tying functions to functions is error-prone e.g., forgetting the release call, exceptional return paths Solution –Design a special adapter class whose constructor and destructor call the key scope entry and exit behaviors –Create a guard object on the program call stack (in a scope) Context limitations –Mainly limited to languages with constructor/destructor

CSE 332: Design Patterns (Part I) Part I: Familiar Design Patterns First, a few more patterns related to course so far –Iterator: access elements sequentially no matter how stored –Adapter: converts interface you get into one you want –Factory method: creates a related type polymorphically Next lecture we’ll examine other important patterns –Bridge: allow interface, implementation to vary separately –Chain of responsibility: give request to chain of handlers –Composite: common interface to composite/simple objects –Interpreter: build a representation for a simple language –Observer: tell registered observers when state changes –Strategy/template method: vary steps/all of an algorithm –Proxy: forward requests from placeholder to another object –Memento: package up object state without violating encapsulation –Visitor: allow various operations on fixed set of objects (2-way dispatch)

CSE 332: Design Patterns (Part I) Iterator Pattern Problem –Want to access aggregated elements sequentially E.g., traverse a list of names and print them out –Don’t want to know details of how they’re stored E.g., in a linked list, or an array, or a balanced binary tree Solution core –Provide a separate interface for iteration over each container Consequences –Frees user from knowing details of how elements are stored –Decouples containers from algorithms (crucial in C++ STL) Examples we’ve seen before –C++ pointers, C++ STL list ::iterator

CSE 332: Design Patterns (Part I) Iterator Pattern Structure Diagram > first() next() is_done() current_item() > create_iterator() creates has-a Each container may have a different iterator type Iterator knows the internals of the container Object-oriented form shown below (for user-defined types) Slightly different with built-in types, templates –E.g., no inheritance relationship, may use traits, etc.

CSE 332: Design Patterns (Part I) Object-Oriented Iterator Example class StringIterator { public: StringIterator (char * s) : s_ (s), current_ (s) {} void first () { current_ = s_; } void next () { ++current_; } bool is_done () { return *current_ == 0; } char * current_item () { return current_; } private: char *s_; char *current_; }; Object-oriented version of iterator is natural to implement as a class in C++ Constructor stores passed pointer to C- style string s, positions current_ at s first (re)positions iterator at the start of the string next moves iterator to the next position is_done tests whether iterator is at the end of the string current_item returns a pointer to the character at the current iterator position

CSE 332: Design Patterns (Part I) Using an Object-Oriented Iterator unsigned int letter_count (StringIterator & si, char c) { unsigned int count = 0; for (si.first (); ! si.is_done ( ); si.next ()) if (*si.current_item () == c) ++count; return count; } Iterators naturally support use in looping constructs Here we show a for loop –first is used to initialize –is_done used for loop test –next used to increment –current_item is used in loop body’s value comparison When the loop completes, the function shown has –Iterated through entire string –Counted occurrences of the character value in the string –Returned the occurrence count

CSE 332: Design Patterns (Part I) Using a Procedural Iterator. unsigned int letter_count (char * si, char * start, char c) { unsigned int count = 0; for (si = start; *si != 0; ++si) if (*si == c) ++count; return count; } This pattern is not limited to C++ or even to object-oriented languages –For example, C code to the left Some changes are needed –Need to pass in start of string (not encapsulated in iterator class) –Syntax for pointer operators instead of method invocations Solution core clearly the same –Program pretty much the same –Result of function is the same –Looks a lot like STL examples

CSE 332: Design Patterns (Part I) Adapter Pattern Problem –Have an object with an interface that’s close to but not exactly what we need Context –Want to re-use an existing class –Can’t change its interface –Impractical to extend class hierarchy more generally Solution –Wrap a particular class or object with the interface needed (2 forms: class form and object forms) Consequences –Implementation you’re given gets interface you want

CSE 332: Design Patterns (Part I) Adapter Pattern Structure Diagram (Class Form) Abstract base class provides desired interface Concrete Impl class provides the implementation Adapter glues them together via inheritance InterfaceImpl method () = 0;impl_method (); Adapter method (); public private

CSE 332: Design Patterns (Part I) Adapter Pattern Structure Diagram (Object Form) Abstract base class provides desired interface Concrete Impl class provides the implementation Adapter class glues them together via delegation Interface Impl method () = 0; impl_method (); Adapter method ();

CSE 332: Design Patterns (Part I) Factory Method Pattern Problem –You want a class to create a related class polymorphically Context –Each class knows which version of the related class it should create Solution –Declare abstract method that derived classes override Consequences –Type created matches type(s) it’s used with Container Iterator * make_iterator()=0; Array Iterator * make_iterator(); Linked_List Iterator * make_iterator(); Iterator first()=0; next()=0; current()=0; is_done()=0; Array_Iterator first(); next(); current(); is_done(); List_Iterator first();next(); current(); is_done();

CSE 332: Design Patterns (Part I) Object-Oriented vs. Generic Variations Use Factory Method pattern if you have inheritance hierarchies of classes (with abstract base classes) Use the Traits idiom when you want a generic programming version of this technique –E.g., when you have unrelated classes capable of providing common interfaces (like STL vectors and linked lists) Traits version relies on templates and compile-time dispatching of calls Inheritance based version relies on run-time dynamic resolution of calls (virtual functions and overriding)

CSE 332: Design Patterns (Part I) Summary We’ve looked at a number of important patterns so far –Singleton: share a class instance across multiple uses –Command: package up a function as an object –Iterator: access elements sequentially no matter how stored –Adapter: converts interface you get into one you want –Factory method: creates a related type polymorphically Next time: Design Patterns II –Bridge: allow interface, implementation to vary separately –Chain of responsibility: give request to chain of handlers –Composite: common interface to composite/simple objects –Interpreter: build a representation for a simple language –Observer: tell registered observers when state changes –Strategy/template method: vary steps/all of an algorithm –Proxy: forward requests from placeholder to another object –Memento: package up object state without violating encapsulation –Visitor: allow various operations on fixed set of objects (2-way dispatch)