Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו...

23
Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 ווו"וby Moshe Fresko
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    218
  • download

    1

Transcript of Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו...

Page 1: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Algorithm Programming 289-211Behavioral Design Patterns

Bar-Ilan University תשס"ו 2005-2006

by Moshe Fresko

Page 2: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Chain of Responsibility Intent

Avoid coupling the sender of a request to its receiver by giving more then one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Motivation A context sensitive Help Facility. To organize help information from most

specific to most general The object that provides the help isn’t known

explicitly to the help initiator.

Page 4: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Chain of Responsibility (Example Structure)

Page 5: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Chain of Responsibility - Example

Page 6: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 7: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Chain of ResponsibilityGeneral Structure

Page 8: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 9: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 10: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Chain of Responsibility// Chain with a new implementation

class 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 11: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 12: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Interpreter Regular Expression Example

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

sequence | repetition | ‘(’ expression ‘)’alternation ::= expression ‘|’ expressionsequence ::= expression ‘&’ expressionrepetition ::= expression ‘*’literal ::= ‘a’ | ‘b’ | ‘c’ | … { ‘a’ | ‘b’ | ‘c’ |

… } *

Page 13: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Interpreter – Example Structure

Page 14: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Interpreter – Possible Structure

Page 15: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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, when The grammar is simple Efficiency is not a critical concern

Page 16: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Interpreter – General Structure

Page 17: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 18: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 19: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

Interpreter – Example

Grammar for Document Searchexpression ::= literal | alternation |

intersectionalternation ::= expression OR expression intersection ::= expression AND

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

Page 20: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 21: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 searchclass 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 22: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 23: Algorithm Programming 2 89-211 Behavioral Design Patterns Bar-Ilan University 2005-2006 תשס " ו by Moshe Fresko.

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 ; }}