Top Banner
02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University חחח"ח2008
50

02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Jan 03, 2016

Download

Documents

Griffin Cobb
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

02 - Behavioral Design Patterns – 1

Moshe Fresko

Bar-Ilan University

תשס"ח

2008

Page 2: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Behavioral Patterns Behavioral Patterns are concerned with algorithms and the assignment of

responsibilities between objects. Not only patterns of objects/classes but also patterns of communication between

them. These patterns are:

Template Method: An abstract definition of an algorithm. Interpreter: Represents a grammar as a class hierarchy and implements an interpreter

as an operation on instances of these classes. Mediator: Provides the indirection needed for loose coupling. Chain of Responsibility: Lets you send requests to an object implicitly through a chain

of candidate objects. Observer: Defines and Maintains dependency between objects. (MVC) Strategy: Encapsulates an algorithm in an Object. Command: Encapsulates a request in an Object. State: Encapsulates the states of an Object so that the Object can change its

behavior when its state object is changes. Visitor: Encapsulates behavior that would otherwise be distributed across classes. Iterator: Abstracts the way you access and traverse objects in an aggregate.

Page 3: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator

Moshe Fresko

Bar-Ilan University

2005-2006 - תשס"ו

Design Patterns Course

Page 4: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator Intent

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Motivation An aggregate object such as a list should give you a way

to access its elements without exposing its internal structure. Moreover you might want to traverse the list in different ways.

We cannot fill the List interface with different traversals we can need.

We may want a couple of traversals pending on the same time.

Page 5: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator

Page 6: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator – Example Structure

Page 7: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator

Use iterator pattern …To access an aggregate object’s contents

without exposing its internal representation.

To support multiple traversals of aggregate objects.

To provide a uniform interface for traversing different aggregate structures (to support polymorphic iteration).

Page 8: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator – General Structure

Page 9: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator Participants

Iterator Defines an interface for accessing and traversing

elements ConcreteIterator

Implements the iterator interface Keeps track of the current position in the traversal

Aggregate Defines an interface method that creates an iterator object

ConcreteAggregate Implements the iterator creation method, and returns an

instance of the proper ConcreteIterator

Page 10: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Iterator

Consequences It supports variants in the traversal of an aggregate Iterators simplify the Aggregate interface More then one traversal can be pending on an aggregate

Implementation Who controls the iteration?

External Iterator: Client controls the iteration Internal Iterator: The Iterator controls the iteration

Who defines the traversal algorithm? The aggregate: This is called a cursor. The iterator.

How robust is the iterator? Modifying an aggregate while traversing it will be dangerous for

iterator. Robust iterator will not be effected by changes.

Page 11: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Java Iterators

interface Collection { … Iterator iterator(); …}

interface Set extends Collection { … Iterator iterator(); …}

interface List extends Collection { … Iterator iterator(); ListIterator listIterator(); ListIterator listIterator(int index); …}

Interface Iterator { boolean hasNext() ; Object next() ; void remove() ;}

Interface ListIterator extends Iterator { boolean hasNext() ; Object next() ; boolean hasPrevious() ; Object previous() ; int nextIndex() ; int previousIndex() ; void remove() ; void set(Object o) ; void add(Object o) ;}

Page 12: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Java Iteratorimport java.util.*; public class IteratorExample { public static void main(String[] args) { List ints = new ArrayList(); for(int i = 0; i < 10; i++) ints.add(new Integer(i)); Iterator e = ints.iterator(); while(e.hasNext()) System.out.println( ((Integer)e.next()).intValue() ) ; } }

Page 13: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Chain of Responsibility

Moshe Fresko

Bar-Ilan University

2005-2006 - תשס"ו

Design Patterns Course

Page 14: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Chain of Responsibility

Use Chain of Responsibility when … More then one object may handle a request, and the

handler isn’t known a-priori. You want to issue a request to one of several objects

without specifying the receiver explicitly. The set of objects that handle a request should be

specified dynamically.

Page 15: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Chain of ResponsibilityGeneral Structure

Page 16: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Chain of Responsibility Participants

Handler (HelpHandler) Defines and interface for handling requests. Implements the successor link.

ConcreteHandler (PrintButton, PrintDialog) Handles requests it is responsible for. Can access its successor. If it does not handle the request, then it forwards it to its

successor. Client

Initiates the request to a ConcreteHandler object on the chain.

Page 17: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Chain of Responsibility

Consequences Reduced Coupling Flexibility in assigning responsibilities to Objects Receipt isn’t guaranteed.

Implementation Implementing the successor chain can be done with a new

implementation or use existing links. Representing Requests may be via an object.

Page 18: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Chain of Responsibility

// Chain with a new implementationclass HelpHandler { private HelpHandler successor = null ; HelpHandler(HelpHandler successor) { this.successor = successor ; } public void handleHelp() {

if (successor!=null) { successor.handleHelp() ; }

}}

// Any relationship (hierarchical or list) like is-a can be used for chaining

Page 19: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter

Moshe Fresko

Bar-Ilan University

2005-2006 - תשס"ו

Design Patterns Course

Page 20: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter Intent

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

Motivation If a particular kind of problem occurs often enough, then it

might be worthwhile to express instances of the problem as sentences in a simple language.

For example: Regular Expressions Document Retrieval Query

Page 21: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter Regular Expression Example

A simple Regular Expression Grammarexpression ::= literal | alternation | sequence |

repetition | ‘(’ expression ‘)’

alternation ::= expression ‘|’ expression

sequence ::= expression ‘&’ expression

repetition ::= expression ‘*’

literal ::= ‘a’ | ‘b’ | ‘c’ | … { ‘a’ | ‘b’ | ‘c’ | … } *

Page 22: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – Example Structure

Page 23: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – Possible Structure

Page 24: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter

Applicability Use Interpreter pattern when there is a language

to interpret, and you can represent statements in the language as abstract syntax trees.

The interpreter works well, whenThe grammar is simpleEfficiency is not a critical concern

Page 25: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – General Structure

Page 26: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter

Participants AbstractExpression (RegularExpression)

Declares an abstract interpret() operation TerminalExpression (LiteralExpression)

Implements the interpret() operation for terminal symbols in the grammar

NonterminalExpression (AlternationExpression, RepetitionExpression, SequenceExpression)

Keeps AbstractExpression for each internal symbol it keeps Implements interpret() operation.

Context Contains information that is global to the interpreter

Client Builds the abstract syntax tree Calls the interpret() operation

Page 27: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter

Consequences It is easy to change and extend the grammar Implementing the grammar is easy Complex grammars are hard to maintain

Implementation Creating the abstract syntax tree Defining the interpret() operation Sharing terminal symbols with the Flyweight pattern

Page 28: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – Example

Grammar for Document Searchexpression ::= literal | alternation | intersection

alternation ::= expression OR expression

intersection ::= expression AND expression

literal ::= ‘a’|‘b’|‘c’|…

literal ::= literal ‘a’|‘b’|‘c’…

Page 29: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – Example

// Interface of a document collectioninterface DocCollection {

int[] getDocNumbersForWord(String word) ;}

// Interface for searching a document colletioninterface DocSearch{

int[] getDocNumbers(DocCollection d) ;}

// A Literal searchclass Literal implements DocSearch{

String word ;Literal(String word)

{ this.word = word ; }public int[] getDocNumbers(DocCollection d)

{ return d.getDocNumbersForWord(this.word) ; }}

Page 30: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – Example

// An alternation searchclass Alternation implements DocSearch{

DocSearch search1=null ;DocSearch search2=null ;Alternation(DocSearch search1, DocSearch search2)

{ this.search1=search1; this.search2=search2; }

public int[] getDocNumbers(DocCollection d){ return Utils.union(search1.getDocNumbers(d),search2.getDocNumbers(d)) ; }

}// An intersection search

class Intersection implements DocSearch{

DocSearch search1=null ;DocSearch search2=null ;Intersection(DocSearch search1, DocSearch search2)

{ this.search1=search1; this.search2=search2; }

public int[] getDocNumbers(DocCollection d){ return

Utils.intersection(search1.getDocNumbers(d),search2.getDocNumbers(d)) ; }}

Page 31: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – Example

// The factory for creating the interpreted DocSearch pointerclass DocSearchInterpreter{ public static DocSearch interpret(String query) { String[] alt = query.split(" OR ") ; DocSearch d = interpretAnd(alt[0]) ; for (int i=1;i<alt.length;++i) d = new Alternation(d,interpretAnd(alt[i])) ; return d ; } private static DocSearch interpretAnd(String query) { String[] alt = query.split(" AND ") ; DocSearch d = interpretOne(alt[0]) ; for (int i=1;i<alt.length;++i) d = new Intersection(d,interpretOne(alt[i])) ; return d ; } private static DocSearch interpretOne(String query) { return new Literal(query.trim()) ; }}

Page 32: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Interpreter – Example // Some utilities for union and // intersection of sorted integer listsclass Utils { public static int[] union(int[] a, int[] b) { List l = new ArrayList() ; int i=0, j=0; while (i<a.length && j<b.length) { if (a[i]==b[j]) { l.add(new Integer(a[i])) ; i++ ; j++ ; continue ; } else if (a[i]<b[j]) { l.add(new Integer(a[i])) ; i++ ; continue ; } else { l.add(new Integer(b[j])) ; j++ ; continue ; } } for (;i<a.length;++i) l.add(new Integer(a[i])) ; for (;j<b.length;++j) l.add(new Integer(b[j])) ; return arrayFromList(l) ; }

public static int[] intersection(int[] a, int[] b) { List l = new ArrayList() ; int i=0, j=0; while (i<a.length && j<b.length) { if (a[i]==b[j]) { l.add(new Integer(a[i])) ; i++ ; j++ ; continue ; } else if (a[i]<b[j]) { i++ ; continue ; } else { j++ ; continue ; } } return arrayFromList(l) ; }private static int[] arrayFromList(List l) { int[] r=new int[l.size()] ; for (int i=0;i<r.length;++i) r[i]=((Integer)l.get(i)).intValue() ; return r ; }}

Page 33: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command

Moshe Fresko

Bar-Ilan University

2005-2006 - תשס"ו

Design Patterns Course

Page 34: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command Pattern

Intent: Encapsulate a request as an Object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Motivation: The Command Pattern lets toolkit objects make requests of

unspecified application objects by turning the request itself into an Object. This object can be stored and passed around.

Page 35: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command - Motivation

Menus can be implemented easily. Each choice in a Menu instance is an instance of MenuItem class.

Page 36: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Motivation

Page 37: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Motivation

Page 38: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Motivation

Page 39: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Applicability

Use Command pattern when you want to Parametrize objects by an action to perform.

(callback function or Interface) Specify, queue and execute requests at different

times. Support undo. Support logging. Structure a system around high-level operations

built on primitive operations.

Page 40: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Structure

Page 41: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Participants Command

Declares an interface for executing an operation. ConcreteCommand

Defines a binding between a receiver object and an action. Implements Execute by invoking the corresponding operations

on Receiver. Client

Creates a ConcreteCommand object and sets its receiver. Invoker

Asks the Command to carry out the request. Receiver

Knows how to perform the operations associated with carrying out a request.

Page 42: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Interactions

Page 43: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Consequences

Command decouples the object that invokes the operation from the one that knows how to perform it.

Commands are first-class objects. They can be manipulated and extended.

You can assemble commands into a composite command.

It's easy to add new Commands, because you don't have to change existing classes.

Page 44: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Implementation

How intelligent should a Command be? Supporting undo and redo. Avoiding error accumulation in the undo

process. Using C++ templates to avoid creating a

Command subclass for every kind of action and receiver.

Page 45: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Sample Code

class Command {

public:

virtual ~Command();

virtual void Execute() = 0;

protected:

Command();

};

Page 46: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Sample Codeclass OpenCommand : public Command {private:

Application* _application;char* _response;

public:OpenCommand(Application*)

{ _application = a; }virtual void Execute()

{ const char* name = AskUser(); Document* document = new Document(name); _application->Add(document); document->Open(); }

protected:virtual const char* AskUser();

};

Page 47: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Sample Code

class PasteCommand : public Command {

private:

Document* _document;

public:

PasteCommand(Document*)

{ _document = doc; }

virtual void Execute()

{ _document->Paste(); }

};

Page 48: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Sample Code

template <class Receiver>class SimpleCommand : public Command {public:

typedef void (Receiver::* Action)();SimpleCommand(Receiver* r, Action a) : _receiver(r), _action(a) { }virtual void Execute()

{ (_receiver->*_action)(); }private:

Action _action;Receiver* _receiver;

};

Page 49: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Sample Code

MyClass* receiver = new MyClass;

// ...

Command* aCommand =

new SimpleCommand<MyClass> (receiver, &MyClass::Action);

// ...

aCommand->Execute();

Page 50: 02 - Behavioral Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.

Command – Sample Codeclass MacroCommand : public Command {private:

List<Command*>* _cmds;public:

MacroCommand();virtual ~MacroCommand();virtual void Add(Command*)

{ _cmds->Append(c); }virtual void Remove(Command*)

{ _cmds->Remove(c); }virtual void Execute()

{ ListIterator<Command*> i(_cmds); for (i.First(); !i.IsDone(); i.Next()) { Command* c = i.CurrentItem();

c->Execute(); } }};