Design Patterns Behavioral Patterns. Chain of Responsibility Avoid coupling the sender of a request to its receiver by giving more than one object a chance.

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

Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
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.
Matt Klein 7/2/2009.  Intent  Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.
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.
Nov, 1, Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven solution to a recurring problem in a specific context and its.
Design Patterns In OPM Presented by: Galia Shlezinger Instructors: Prop. Dov Dori, Dr. Iris Berger.
BehavioralCmpE196G1 Behavioral Patterns Chain of Responsibility (requests through a chain of candidates) Command (encapsulates a request) Interpreter (grammar.
Design Patterns CS is not simply about programming
Oct, 16, Design Patterns PROBLEM CONTEXT SOLUTION A design pattern documents a proven solution to a recurring problem in a specific context and.
Algorithm Programming Behavioral Design Patterns Bar-Ilan University תשס " ו by Moshe Fresko.
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.
Behavioral Patterns C h a p t e r 5 – P a g e 128 BehavioralPatterns Design patterns that identify and realize common interactions between objects Chain.
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
1 GoF Template Method (pp ) GoF Strategy (pp ) PH Single User Protection (pp ) Presentation by Julie Betlach 6/08/2009.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
More Design Patterns In Delphi Jim Cooper Falafel Software Session Code: D3.03 Track: Delphi.
CS 210 Introduction to Design Patterns September 28 th, 2006.
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
Lexi case study (Part 2) Presentation by Matt Deckard.
CS 210 Adapter Pattern October 19 th, Adapters in real life Page 236 – Head First Design Patterns.
Computing IV Singleton Pattern Xinwen Fu.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
ECE450S – Software Engineering II
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
Behavioral Pattern: Strategy C h a p t e r 5 – P a g e 205 The Open-Closed Principle advocates designing software in such a way that it will absorb new.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
CS 4233 Review Feb February Review2 Outline  Previous Business – My.wpi.edu contains all grades to date for course – Review and contact.
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.
Behavioural Design Patterns Quote du jour: ECE450S – Software Engineering II I have not failed. I've just found 10,000 ways that won't work. - Thomas Edison.
DESIGN PATTERNS -BEHAVIORAL PATTERNS WATTANAPON G SUTTAPAK Software Engineering, School of Information Communication Technology, University of PHAYAO 1.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department.
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.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
Behavioral Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
Using Software Design Patterns Bill Anderson. About me Fox developer since 1987 Fox developer since 1987 Program Director, Los Angeles Visual Foxpro Developers.
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
SOFTWARE DESIGN AND ARCHITECTURE LECTURE 31. Review Creational Design Patterns – Singleton Pattern – Builder Pattern.
Interface Patterns. Adapter Provides the interface a client expects, using the services of a class with a different interface Note Avoid using object.
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.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
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.
Behavioural Patterns GoF pg Iterator GoF pg. 257 – 271 Memento GoF pg By: Dan Sibbernsen.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
Design Patterns. Outline Purpose Purpose Useful Definitions Useful Definitions Pattern Overview Pattern Overview.
Design Patterns: Behavioral Design Patterns General and reusable solutions to common problems in software design Software University
OBSERVER PATTERN OBSERVER PATTERN Presented By Presented By Ajeet Tripathi ISE
Overview of Behavioral Patterns ©SoftMoore ConsultingSlide 1.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Jim Fawcett CSE776 – Design Patterns Summer 2006
Chapter 10 Design Patterns.
Software Design Patterns
Jim Fawcett CSE776 – Design Patterns Fall 2016
Introduction to Design Patterns
Behavioral Design Patterns
object oriented Principles of software design
Object Oriented Design Patterns - Behavioral Patterns
Behavioral Design Pattern
Introduction to Design Patterns
Lists CMSC 202, Version 4/02.
Presentation transcript:

Design Patterns Behavioral Patterns

Chain of Responsibility Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it Use When: –more than on object may handle a request, and the handler isn't known a priori –When you want to issue a request to one of several objects without specifying the receiver explicitly –When the set of objects that can handle a request should be specified dynamically Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it Use When: –more than on object may handle a request, and the handler isn't known a priori –When you want to issue a request to one of several objects without specifying the receiver explicitly –When the set of objects that can handle a request should be specified dynamically

Chain of Responsibility

Command Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations Use When you need an action as a parameter Commands replace callback functions When you need to specify, queue, and execute requests at different times When you need to support undo When you need to support logging changes Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations Use When you need an action as a parameter Commands replace callback functions When you need to specify, queue, and execute requests at different times When you need to support undo When you need to support logging changes

Command

Interpreter Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language you create a class for each rule The classes can be used to construct a tree that represents elements of the language Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language you create a class for each rule The classes can be used to construct a tree that represents elements of the language

Interpreter

Iterator Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation methods: –movenext() –getcur() –eof() Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation methods: –movenext() –getcur() –eof()

Iterator

The Abstract Node of the List Key is a type which the list is orderd by In most cases its a unique member of the data class type In spit of that Key type can also be more than one member of the data class type ( don’t forget to overload operator > or operator = = ) Data is a poiner to the real object i.e we have here a list of poinetrs to our objects Key is a type which the list is orderd by In most cases its a unique member of the data class type In spit of that Key type can also be more than one member of the data class type ( don’t forget to overload operator > or operator = = ) Data is a poiner to the real object i.e we have here a list of poinetrs to our objects struct Record { Key key; Data data; Record *next; }; struct Record { Key key; Data data; Record *next; };

More Private Members bool find_record(const Key& ); Record *first; Record *precedingRecord *candidate Using these three

Public Members bool get_data(const Key &,Data &) bool add_data(const Key &,Data &) bool remove_data(const key &) void operator &) bool get_data(const Key &,Data &) bool add_data(const Key &,Data &) bool remove_data(const key &) void operator &)

template class List { struct Record { // The abstract node of the list Key key; Data data; Record *next; }; Record *first; // head of the list Record *candidate, *preceding; // for find bool find_record(const Key& ); public: List () : first(NULL) {} ~List() ; bool get_data(const Key&,Data &); bool add_data(const Key&,const Data& ); bool remove_data(const Key& ); friend ostream& operator & ); template class List { struct Record { // The abstract node of the list Key key; Data data; Record *next; }; Record *first; // head of the list Record *candidate, *preceding; // for find bool find_record(const Key& ); public: List () : first(NULL) {} ~List() ; bool get_data(const Key&,Data &); bool add_data(const Key&,const Data& ); bool remove_data(const Key& ); friend ostream& operator & );

Get Data template inline bool List ::get_data(const Key& key,Data &data) { if( find_record(key) == true){ data = candidate->data; return true; } return false; } template inline bool List ::get_data(const Key& key,Data &data) { if( find_record(key) == true){ data = candidate->data; return true; } return false; }

Add Data template inline bool List ::add_data(const Key& key,const Data& data) { Record *pt; if( (find_record(key) == true)) return false; pt = new Record; assert(pt != NULL); pt->key = key; pt->data = data; if(preceding == NULL){ pt->next = first; first = pt; return true; } pt->next = preceding->next; preceding->next = pt; return true; } template inline bool List ::add_data(const Key& key,const Data& data) { Record *pt; if( (find_record(key) == true)) return false; pt = new Record; assert(pt != NULL); pt->key = key; pt->data = data; if(preceding == NULL){ pt->next = first; first = pt; return true; } pt->next = preceding->next; preceding->next = pt; return true; }

Remove Data template inline bool List ::remove_data(const Key& key) { Record *free_me; if( find_record(key) == false ) return false; free_me = candidate; if(preceding == NULL) first = candidate->next; else preceding->next = candidate->next; delete free_me->data; delete free_me; return true; } template inline bool List ::remove_data(const Key& key) { Record *free_me; if( find_record(key) == false ) return false; free_me = candidate; if(preceding == NULL) first = candidate->next; else preceding->next = candidate->next; delete free_me->data; delete free_me; return true; }

Find Record template bool List :: find_record(const Key& search_key) { preceding = candidate = NULL; if(first == NULL) return false; // list is empty for(candidate = first; ; ){ if(candidate->key == search_key) return true; if(candidate->key > search_key) return false; if(candidate->next == NULL) { preceding = candidate; return false; } preceding = candidate; candidate = candidate->next; } template bool List :: find_record(const Key& search_key) { preceding = candidate = NULL; if(first == NULL) return false; // list is empty for(candidate = first; ; ){ if(candidate->key == search_key) return true; if(candidate->key > search_key) return false; if(candidate->next == NULL) { preceding = candidate; return false; } preceding = candidate; candidate = candidate->next; }

Print All Data template ostream& operator & l) { for(List ::ConstIterator i(l); i ; i++) out << *(*i); return out; } template ostream& operator & l) { for(List ::ConstIterator i(l); i ; i++) out << *(*i); return out; }

Delete All Data template List ::~List() { Record *curr,*free_me; if (first == NULL) return; for(curr = first; ; ){ free_me = curr; curr = curr->next; delete free_me; if(curr == NULL) break; } first = NULL; } template List ::~List() { Record *curr,*free_me; if (first == NULL) return; for(curr = first; ; ){ free_me = curr; curr = curr->next; delete free_me; if(curr == NULL) break; } first = NULL; }

List::Iterator class ConstIterator { private: const List& m_list; Record *m_current; public: ConstIterator(const List& list) : m_list(list),m_current(NULL) {m_current = m_list.first;} ConstIterator& operator++() { assert(m_current!= NULL); m_current = m_current->next; return *this; } class ConstIterator { private: const List& m_list; Record *m_current; public: ConstIterator(const List& list) : m_list(list),m_current(NULL) {m_current = m_list.first;} ConstIterator& operator++() { assert(m_current!= NULL); m_current = m_current->next; return *this; }

const ConstIterator operator++(int) { assert(m_current!= NULL); ConstIterator i(*this); m_current = m_current->next; return i; } operator int() const {return m_current != NULL;} const Data& operator *() { return m_current->data;} const Data& data() {return m_current->data;} const Key& key() {return m_current->key;} }; const ConstIterator operator++(int) { assert(m_current!= NULL); ConstIterator i(*this); m_current = m_current->next; return i; } operator int() const {return m_current != NULL;} const Data& operator *() { return m_current->data;} const Data& data() {return m_current->data;} const Key& key() {return m_current->key;} };

The following operators must be defined for the Key type: =(assignment) // This means also copy-constructor = =(equality) >(greater than) The following operators must be defined for the Data type: << (output) The following operators must be defined for the Key type: =(assignment) // This means also copy-constructor = =(equality) >(greater than) The following operators must be defined for the Data type: << (output) Attention !! Can you Tell Why ?

Using example class Car{ String name; int eng; int price; public: Car(String s="",int e=0,int p=0):name(s),eng(e),price(p){} friend ostream& operator<<(ostream& out,const Car& c) { return out << "Car Name: "<< c.name << endl << "Eng : " << c.eng << " cc" << endl << "Value : " << c.price << " nis."<< endl; } String get_name() {return name;} }; class Car{ String name; int eng; int price; public: Car(String s="",int e=0,int p=0):name(s),eng(e),price(p){} friend ostream& operator<<(ostream& out,const Car& c) { return out << "Car Name: "<< c.name << endl << "Eng : " << c.eng << " cc" << endl << "Value : " << c.price << " nis."<< endl; } String get_name() {return name;} };

class Student{ int id; String name; public: Student(int i=0,String str=""):id(i),name(str) { } Student(istream& std); friend ostream& operator<<(ostream& out,const Student& st) { return out << "Student id : " << st.id << endl << "Student name : " << st.name <<endl; } int get_id() {return id;} }; class Student{ int id; String name; public: Student(int i=0,String str=""):id(i),name(str) { } Student(istream& std); friend ostream& operator<<(ostream& out,const Student& st) { return out << "Student id : " << st.id << endl << "Student name : " << st.name <<endl; } int get_id() {return id;} }; List students; List cars; List students; List cars; Declartion Of Lists

Using The Iterator for(List ::ConstIterator it1(students); it1 ; it1++) delete(*it1); for(List ::ConstIterator it2(cars); it2 ; it2++) delete(*it2); for(List ::ConstIterator it1(students); it1 ; it1++) delete(*it1); for(List ::ConstIterator it2(cars); it2 ; it2++) delete(*it2);

Mediator Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently Defines an interface for communicating with Colleague objects Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently Defines an interface for communicating with Colleague objects

Mediator

Memento Without violating encapsulation, capture and externalize an object's internal state so that the object can be returned to this state later Allow undos, rollbacks, etc. But we have Command and Clone, why do we need another pattern for undo? –Clone can be more expensive than we need Only part of the state of an object may change, cloning will copy all the state Cloning can be hard to implement Replacing an object with a clone does not work when other objects have references to the object to rollback Without violating encapsulation, capture and externalize an object's internal state so that the object can be returned to this state later Allow undos, rollbacks, etc. But we have Command and Clone, why do we need another pattern for undo? –Clone can be more expensive than we need Only part of the state of an object may change, cloning will copy all the state Cloning can be hard to implement Replacing an object with a clone does not work when other objects have references to the object to rollback

Memento

Observer Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Use the Observer pattern: –When an abstraction has two aspects, one dependent on the other. –When a change to one object requires changing others, and you don't how many objects need to be changed –When an object should be able to notify other objects without making assumptions about who these objects are. Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Use the Observer pattern: –When an abstraction has two aspects, one dependent on the other. –When a change to one object requires changing others, and you don't how many objects need to be changed –When an object should be able to notify other objects without making assumptions about who these objects are.

Observer

State Allow an object to alter its behavior when its internal state changes. The object will appear to change its class Use the State pattern in either of the following cases: –An object's behavior depends on its state, and it must change its behavior at run-time depending on that state. –Operations have large, multipart conditional statements that depend on the object's state. Often, several operations will contain this same conditional structure Allow an object to alter its behavior when its internal state changes. The object will appear to change its class Use the State pattern in either of the following cases: –An object's behavior depends on its state, and it must change its behavior at run-time depending on that state. –Operations have large, multipart conditional statements that depend on the object's state. Often, several operations will contain this same conditional structure

State

Strategy Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it The Strategy pattern should only be used when the variation in behavior is relevant to clients. If this criteria is not satisfied, the additional abstraction and effort necessary to implement the Strategy pattern is not justified Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it The Strategy pattern should only be used when the variation in behavior is relevant to clients. If this criteria is not satisfied, the additional abstraction and effort necessary to implement the Strategy pattern is not justified

Strategy

Template Method Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Template Method

Visitor Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates Use When an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates Use When an object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes

The Problem We have a set of Objects. We are writing several algorithms working with these objects. We don’t want the objects to be responsible for their part in the algorithm –It does not look good –Several teams are developing with these classes and we can’t change them easily. We have a set of Objects. We are writing several algorithms working with these objects. We don’t want the objects to be responsible for their part in the algorithm –It does not look good –Several teams are developing with these classes and we can’t change them easily.

Example - Animal hospital We have many animals We want to create a dentist class that can treat any animal’s tooth ache Addition of new animals is not so probable Addition of new types of doctors is probable. We have many animals We want to create a dentist class that can treat any animal’s tooth ache Addition of new animals is not so probable Addition of new types of doctors is probable.

Solution - 1 Let the damn horse treat itself …. class Horse : public Animal { public: void CureTeeth() { } class Animal { public: void CureTeeth()=0; } Looks ugly !

Problems It does not make any sense. –Heeling teeth is not one of the things horses (or any animals) do to themselves. Maybe we can’t change the animal classes –Other groups might be working on it simultaneously. It does not make any sense. –Heeling teeth is not one of the things horses (or any animals) do to themselves. Maybe we can’t change the animal classes –Other groups might be working on it simultaneously.

Solution - 2 Void foo(Animal x) { if (x instanceof Horse) { //give a horse teeth treatment } else if (x instanceof Mouse) { //give a mouse teeth treatment } … }

Problems Looks bad! Slow RTTI usage is not recommended in good design. Looks bad! Slow RTTI usage is not recommended in good design.

A Better Idea - Use Visitor

How does it work ?