Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Slides:



Advertisements
Similar presentations
Behavioral Design Patterns May 5, 2015May 5, 2015May 5, 2015.
Advertisements

 Recent researches show that predicative programming can be used to specify OO concepts including classes, objects, interfaces, methods, single and multiple.
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.
Iterators T.J. Niglio Computer & Systems Engineering Fall 2003 Software Design & Documentation Object Behavioral.
Copyright © 1995 –2004 Active Frameworks Inc. - All Rights Reserved - V2.0Behavioral Patterns - Page L8-1 PS95&96-MEF-L15-1 Dr. M.E. Fayad Creationa l.
BehavioralCmpE196G1 Behavioral Patterns Chain of Responsibility (requests through a chain of candidates) Command (encapsulates a request) Interpreter (grammar.
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.
Design Patterns.
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.
CS 210 Introduction to Design Patterns September 28 th, 2006.
UML - Patterns 1 Design Patterns. UML - Patterns 2 Becoming Good OO Developers Developing good OO Software is hard Takes a lot of time to take advantage.
SWE 316: Software Design and Architecture Objectives Lecture # 15 Behavioral Design Patterns SWE 316: Software Design and Architecture  To learn the behavioral.
Chapter 9: The Iterator Pattern
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.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
ECE450S – Software Engineering II
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Command Pattern.
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.
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.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
DESIGN PATTERNS -BEHAVIORAL PATTERNS WATTANAPON G SUTTAPAK Software Engineering, School of Information Communication Technology, University of PHAYAO 1.
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.
Design Patterns Introduction
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.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
© SERG Software Design (OOD Patterns) Pg 1 Object-Oriented Design Patterns Topics in Object-Oriented Design Patterns Material drawn from [Gamma95,Coplien95]
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.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
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
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.
OBSERVER PATTERN OBSERVER PATTERN Presented By Presented By Ajeet Tripathi ISE
Overview of Behavioral Patterns ©SoftMoore ConsultingSlide 1.
1 Iterator Pattern (A Behavioral Pattern) Prepared by: Neha Tomar.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
February 23, 2009Observer Pattern, OOA&D, Rubal Gupta, CSPP, Winter ‘09 Observer Pattern Defines a “one-to-many” dependency between objects so that when.
Review of last class. Design patterns CreationalStructuralBehavioral Abstract Factory Builder Factory Singleton etc. Adapter Bridge Composite Decorator.
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Chapter 10 Design Patterns.
Introduction to Design Patterns
Behavioral Design Patterns
Software Design and Architecture
Chapter 9 Behavioral Design Patterns
Observer Pattern 1.
Behavioral Patterns Part-I introduction UNIT-VI
The iterator and memento patterns
Design pattern Lecture 9.
Strategy Pattern Jim Fawcett CSE776 – Design Patterns Fall 2014.
Presentation transcript:

Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015

Behavioral Patterns – 1 Command Command Iterator Iterator Mediator Mediator Observer Observer Strategy Strategy Template Method Template Method

Behavioral Patterns – 2 Chain of Responsibility Chain of Responsibility Interpreter Interpreter Momento Momento State State Visitor Visitor

Iterator Design Purpose Design Purpose –Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation Design Pattern Summary Design Pattern Summary –Encapsulate the iteration in a class pointing (in effect) to an element of the aggregate

Iterator Interface Iterator { // move to first item: void first(); // if it is at last item: boolean isDone(); // move point to next item: void next(); // Return the current: Object currentItem(); }

Using Iterator /* To perform desiredOperation() on items in the container according to the iteration (order) i: */ Iterator i = IteratorObject; for(i.first(); !i.isDone(); i.next()) desiredOperation(i.currentItem());

Iterator Sample Code // Suppose that we have iterators for forward and // backward order: we can re-use print_employees() List employees = new List(); Iterator fwd = employees.createForwardIterator(); Iterator bckwd = employees.createBackwardIterator(); // print from front to back client.print_employees(fwd); // print from back to front client.print_employees(bckwd);

Using Iterator Class Client extends … { print_employees(Iterator it) { for(it.first(); !it.isDone(); it.next()) { print(i.currentItem()); } // other operations }

Iterator Class Model ClientIterator first() next() isDone() currentItem() Container createIterator() append() remove() ConcreteIterator return new ConcreteIterator(this) ConcreteContainer createIterator()

Iterator - Question What is the difference between the two clients Class Client1 { void operation( Container c) { Iterator it = c.createIterator(); for (it.first(); it.isDone(); it.next()) { Object item = it.currentItem(); // process item } } Class Client2 { void operation( Iterator it) { for (it.first(); it.isDone(); it.next()) { Object item = it.currentItem(); // process item } }

Iterator - Question Client1 IteratorContainer Client2 Client1 is dependent upon two interfaces: Iterator and Container Client2 is dependent upon only one interface: Iterator

Iterator in Java - 1 Interface Iterator { // check if there are more elements. boolean hasNext();hasNext // Returns the next element in the iteration. E next() // Removes from the underlying collection next // the last element returned by the iterator // (optional operation). // (optional operation). void remove(); remove }

Iterator in Java - 2 import java.util.Iterator; public class ArrayListViaListWithIterator { private Node head, tail; private int count; public ArrayListViaLinkedListWithInnerIterator() { head = null; tail = null; count = 0; } public Iterator iterator() { return new ALIterator(); } public void add(int i, E e) { … } public E get(int i) { … } public boolean isEmpty() { … } public E remove(int i) { … } public E set(int i, E e) { … } public int size() { … }

Iterator in Java - 3 private class Node { private E item; private Node next; Node(E i, Node n) { … } public E getItem() { … } public void setItem(E item) {{ … } public Node getNext() { … } public void setNext(Node next) { … } }

Iterator in Java - 4 private class ALIterator implements Iterator { private Node cursor; public AIIterator() { cursor = head; } public boolean hasNext() { return cursor != null; } public E next() { Node tmp = cursor; cursor = cursor.getNext(); return tmp.getItem(); } public void remove() { throw new RuntimeException("not supported"); } } // end of Iterator } // end of ArrayList

Observer Design Purpose Design Purpose –Arrange for a set of objects to be affected by a single object. Design Pattern Summary Design Pattern Summary –The single object aggregates the set, calling a method with a fixed name on each member.

Observer - example

Observer - Structure 1..n for o: observers o.update(this); observers Subject attach(Observer) detach(Observer) notify() Observer update(subject) ConcreteSubject subjectState getState() setState() ConcreteObserver observerState update(Subject s) // change state notify(); … s.getState(); …

Observer: Sequence diagram ClientO1:Observer:SubjectO2: Observer setState() notify() getState() update()

Observer in Java Observable notifyObservers() attach(Observer) detach(Observer) Observer update(Observable, Object ) MyObservable subjectState MyConcreteObserver observerState update(…) subject

Observer : Key Concept -- to keep a set of objects up to date with the state of a designated object.

Mediator Design Purpose Design Purpose –Avoid references between dependent objects. Design Pattern Summary Design Pattern Summary –Capture mutual behavior in a separate class.

Mediator - example

Mediator - Model MediatorColleague ConcreteMediator Colleague_BColleague_A

Mediator Sequence Diagram ClientA:Colleague_A:Mediator B: Colleague_B request() takeAction_1() mediate() :MediatorC: Colleague_A takeAction_2() takeAction_3()

Key Concept: Mediator -- to capture mutual behavior without direct dependency.

Command Design Purpose Design Purpose –Increase flexibility in calling for a service e.g., allow undo-able operations. Design Pattern Summary Design Pattern Summary –Capture operations as classes.

Command - Structure Client Invoker +request() ConcreteCommand execte() State Command execute(); receiver.action() receiver Receiver action()

Command – Sequence Diagram C: ConcreteCmdR:Receiver:ClientInvoker new ConcreteCmd( R ) action() execute() new Invoker( C )

A B: A composed in B Command - Example Cut:Button Clicked() CopyCommand execte() Command execute(); doc.copy() doc Document copy() cut() command command.execute() CutCommand execte() doc doc.cut() Copy:Button Clicked() command.execute() command Cut:MenuItem Selected() command.execute()

Command – Setup C:CopyCommandd:Doc X:CutCommand new Doc() aClient new CutCommand( d ) new CopyCommand( d ) Cut:Button Copy:ButtonCut:MenuItem new MenuItem( x ) new Button( x ) new Button( c )

Command – Sequence Diagram Cut:ButtonCopyCommandCommand DocumentCutCommandCopy:ButtonCut:MenuItem selected() execute() cut() clicked() cut() execute() clicked() copy() execute()

Key Concept - Command -- to avoid calling a method directly (e.g., so as to record or intercept it).

Strategy Design Purpose Design Purpose –Allow the algorithm vary independently from clients that use it Design Pattern Summary Design Pattern Summary –Define a family of algorithms, encapsulate each one, and make them interchangeable

Strategy - Example PlayerPool chooseTwo() Sorter sort() MergerSorter sort() BubbleSorter sort()... sorter.sort();... sorter

Strategy - Model Context contextInterface() Strategy Algorithm() ConcreateStrategyA algorithm() strategy ConcreateStrategyB algorithm() ConcreateStrategyC algorithm()

Strategy - participants Strategy (Sorter) Strategy (Sorter) –Declare an interface for the family of algorithms ConcreteStrategy (BubbleSort and MergeSort) ConcreteStrategy (BubbleSort and MergeSort) –Implementations of the algorithms. Context (PlayerPool) Context (PlayerPool) –Configured with a ConcreteStrategy object –Maintains a reference to a Strategy object –May define an interface that lets Strategy to access its data Collaborations Collaborations –Strategy and Context interact to implement the chosen algorithm. A context may make itself access to the algorithm –A context forwards requests from its clients to its strategy. Clients usually decide which ConcreteStrategy to use for the given context

Strategy – sample code Class PlayerPool { ArrayList players; Comparator c; Sorter sorter; PlayerPool(Comparator c, Sorter s) { this.c = c; this.sorter = s; } Player[] chooseTwo() { sorter.sort(players, c); players[0] = players.remove(); players[1] = players.remove(); return players; } Interface Sorter { void sort(List list, Comparator c) } Class BubbleSort implements Sorter { void sort(List l, Comparator c) } Class MergeSort implements Sorter { void sort(List l, Comparator c) } Class Client { void main() { Player players[2]; Comparator c = new PriorityComp(); Sorter s = new BubbleSort(); PlayerPool vip = new PlayerPool(c, s); players = vip.chooseTwo(); // use players to form a game } Actually, Comparator for sort() is a strategy in this example

Template Method Design Purpose Design Purpose –Allow subclasses to redefine certain steps of an algorithm without changing the algorithm’s structure Design Pattern Summary Design Pattern Summary –Define the skeleton of an algorithm in an operations, deferring some steps to subclasses

Template Method - Example Document save() open() close() read() App addDoc() openDoc() createDoc() canOpenDoc() MyApp createDoc() canOpenDoc() docs MyDocument read() return new MyDocument()

Template Method - example Class App { List docs; void openDoc(String file) { if (!canOpenDoc(file)) { // cannot handle this doc return; } Document doc = createDoc(file); docs.add(doc); doc.open(); doc.read(); } The openDoc() of App is a template method which uses steps (canOpenDoc ()and createDoc()) that are provided by subclasses (MyApp) The openDoc() of App is a template method which uses steps (canOpenDoc ()and createDoc()) that are provided by subclasses (MyApp)

Template Method - Model AbstractClass templateMethod() primitiveOperation1() primitiveOperation2() ConcreteClass primitiveOperation1() primitiveOperation2() { // other operations primitiveOperation1(); primitiveOperations(); }

Template Method - participants AbstractClass (App) AbstractClass (App) –Define an algorithm as an operation which uses abstract primitive operations (as steps of the algorithm) that are to be implemented by subclasses of AbstractClass –Template method may call other operations defined in AbstractClass ConcreteClass (MyApp) ConcreteClass (MyApp) –Implement the abstract primitive operations that are used in the template method. Collaborations Collaborations –ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm.

Iterator visits members of a collection Iterator visits members of a collection Mediator captures behavior among peer objects Mediator captures behavior among peer objects Observer updates objects affected by a single object Observer updates objects affected by a single object Command captures function flexibly (e.g. undo-able) Command captures function flexibly (e.g. undo-able) Summary

Other Patterns Chain of Responsibility 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 Interpreter Interpreter –Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language

Other Patterns Memento Memento –Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later State State –Allow an object to alter its behavior when its internal state changes.

Other Patterns Strategy Strategy –Define a family of algorithms, encapsulate each one, and make them interchangeable. Template Method Template Method –Define the skeleton of an algorithm in an operation, deferring some steps to subclasses

Other Patterns Visitor Visitor –Represent an operation to be performed on the elements of an object structure. A new operation may be encapsulated in a Visitor without the need to change the classes of the elements which it operates on