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

51
Behavioral Design Behavioral Design Patterns Patterns June 15, 2022 June 15, 2022

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

Page 1: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Behavioral Design Behavioral Design PatternsPatterns

April 20, 2023April 20, 2023

Page 2: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Behavioral Patterns – Behavioral Patterns – 11 CommandCommand IteratorIterator MediatorMediator ObserverObserver StrategyStrategy Template MethodTemplate Method

Page 3: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Behavioral Patterns – Behavioral Patterns – 22 Chain of ResponsibilityChain of Responsibility InterpreterInterpreter MomentoMomento StateState VisitorVisitor

Page 4: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

IteratorIterator

Design PurposeDesign Purpose– Provide a way to access the Provide a way to access the

elements of an aggregate object elements of an aggregate object sequentially without exposing its sequentially without exposing its underlying representationunderlying representation

Design Pattern SummaryDesign Pattern Summary– Encapsulate the iteration in a Encapsulate the iteration in a

class pointing (in effect) to an class pointing (in effect) to an element of the aggregateelement of the aggregate

Page 5: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

IteratorIterator

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();

}

Page 6: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Using IteratorUsing Iterator

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

desiredOperation(i.currentItem());

Page 7: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator Sample CodeIterator 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);

Page 8: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Using IteratorUsing Iterator

Class Client extends … {

print_employees(Iterator it) { for(it.first(); !it.isDone(); it.next()) {

print(i.currentItem()); } }

// other operations

}

Page 9: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator Class ModelIterator Class ModelClient

Iteratorfirst()next()isDone()currentItem()

ContainercreateIterator()append()remove()

ConcreteIterator

return new ConcreteIterator(this)

ConcreteContainer

createIterator()

Page 10: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator - QuestionIterator - Question

What is the difference between the two clientsWhat is the difference between the two clientsClass Client1 {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 {Class Client2 {void operation( Iterator it) {for (it.first(); it.isDone(); it.next()) { Object item = it.currentItem(); // process item }}}}

Page 11: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator - QuestionIterator - Question

Client1

Iterator Container

Client2

Client1 is dependent upon two interfaces: Iterator and Container

Client2 is dependent upon only one interface: Iterator

Page 12: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator in Java - 1Iterator in Java - 1

Interface Iterator<E> {Interface Iterator<E> {

// check if there are more elements. // check if there are more elements.

boolean hasNext();

// Returns the next element in the iteration. // Returns the next element in the iteration.

E E next() () // Removes from the underlying collection // Removes from the underlying collection

// the last element returned by the iterator// the last element returned by the iterator

// (optional operation).  // (optional operation).                      

void void remove();();

} }                     

Page 13: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator in Java - 2Iterator in Java - 2

import java.util.Iterator;

public class ArrayListViaListWithIterator<E> { private Node head, tail; private int count; public ArrayListViaLinkedListWithInnerIterator() { head = null; tail = null; count = 0; } public Iterator<E> 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() { … }

Page 14: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator in Java - 3Iterator 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) { … } }

Page 15: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Iterator in Java - 4Iterator in Java - 4 private class ALIterator implements Iterator<E> { 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

Page 16: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

ObserverObserver

Design PurposeDesign Purpose– Arrange for a set of objects to Arrange for a set of objects to

be affected by a single object.be affected by a single object. Design Pattern SummaryDesign Pattern Summary

– The single object aggregates the The single object aggregates the set, calling a method with a set, calling a method with a fixed name on each member.fixed name on each member.

Page 17: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Observer - exampleObserver - example

Page 18: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Observer - StructureObserver - Structure

1..n

for o: observers o.update(this);

observers

Subjectattach(Observer)detach(Observer)notify()

Observerupdate(subject)

ConcreteSubject

subjectStategetState()setState()

ConcreteObserver

observerStateupdate(Subject s)

// change statenotify();

…s.getState();…

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

Observer: Sequence Observer: Sequence diagramdiagram

Client O1:Observer

:Subject O2: Observer

setState() notify()

getState()

getState()

update()

update()

Page 20: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Observer in Observer in JavaJavaObservablenotifyObservers()attach(Observer)detach(Observer)

Observerupdate(Observable, Object )

MyObservablesubjectState

MyConcreteObserverobserverStateupdate(…)

subject

Page 21: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

ObserverObserver: Key Concept: Key Concept

-- to keep a set of objects up to date with the state of a designated object.

Page 22: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

MediatorMediator

Design PurposeDesign Purpose– Avoid references between Avoid references between

dependent objects.dependent objects. Design Pattern SummaryDesign Pattern Summary

– Capture mutual behavior in a Capture mutual behavior in a separate class.separate class.

Page 23: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Mediator - exampleMediator - example

Page 24: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Mediator - exampleMediator - example

Page 25: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Mediator - exampleMediator - example

Page 26: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Mediator - exampleMediator - example

Page 27: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Mediator - ModelMediator - Model

Mediator Colleague

ConcreteMediator

Colleague_BColleague_A

Page 28: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Mediator Sequence Mediator Sequence DiagramDiagram

Client A:Colleague_A

:Mediator

B: Colleague_B

request()

takeAction_1()

mediate()

:Mediator

C: Colleague_A

takeAction_2()

takeAction_3()

Page 29: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Key Concept: MediatorKey Concept: Mediator

-- to capture mutual behavior without direct dependency.

Page 30: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

CommandCommand

Design PurposeDesign Purpose– Increase flexibility in calling for Increase flexibility in calling for

a service e.g., allow undo-able a service e.g., allow undo-able operations.operations.

Design Pattern SummaryDesign Pattern Summary– Capture operations as classes.Capture operations as classes.

Page 31: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Command - Command - StructureStructure

Client Invoker+request()

ConcreteCommand

execte()State

Commandexecute();

receiver.action()

receiverReceiveraction()

Page 32: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Command – Sequence Command – Sequence DiagramDiagram

C: ConcreteCmd

R:Receiver :Client Invoker

new ConcreteCmd( R )

action()execute()

new Invoker( C )

Page 33: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

A B: A composed in B

Command - ExampleCommand - Example

Cut:ButtonClicked()

CopyCommand

execte()

Commandexecute();

doc.copy()

doc

Documentcopy()cut()

command

command.execute()

CutCommandexecte()

doc

doc.cut()

Copy:Button

Clicked()

command.execute()

command

Cut:MenuItem

Selected()

command.execute()

Page 34: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Command – SetupCommand – Setup

C:CopyCommand

d:Doc

X:CutCommand

new Doc()

aClient

new CutCommand( d )

new CopyCommand( d )

Cut:Button

Copy:Button

Cut:MenuItem

new MenuItem( x )

new Button( x )

new Button( c )

Page 35: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Command – Sequence Command – Sequence DiagramDiagram

Cut:Button

CopyCommand

Command

DocumentCutCommand

Copy:Button

Cut:MenuItem

selected() execute()cut()

clicked()cut()

execute()

clicked()copy()

execute()

Page 36: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Key Concept - Key Concept - CommandCommand

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

Page 37: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

StrategyStrategy

Design PurposeDesign Purpose– Allow the algorithm vary Allow the algorithm vary

independently from clients that independently from clients that use ituse it

Design Pattern SummaryDesign Pattern Summary– Define a family of algorithms, Define a family of algorithms,

encapsulate each one, and make encapsulate each one, and make them interchangeablethem interchangeable

Page 38: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Strategy - ExampleStrategy - Example

PlayerPoolchooseTwo(

)

Sortersort()

MergerSortersort()

BubbleSortersort()

... sorter.sort();...

sorter

Page 39: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Strategy - ModelStrategy - Model

ContextcontextInterfac

e()

StrategyAlgorithm()

ConcreateStrategyA

algorithm()

strategy

ConcreateStrategyB

algorithm()

ConcreateStrategyC

algorithm()

Page 40: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Strategy - participantsStrategy - participants

Strategy (Sorter)Strategy (Sorter)– Declare an interface for the family of algorithmsDeclare an interface for the family of algorithms

ConcreteStrategy (BubbleSort and MergeSort)ConcreteStrategy (BubbleSort and MergeSort)– Implementations of the algorithms.Implementations of the algorithms.

Context (PlayerPool)Context (PlayerPool)– Configured with a ConcreteStrategy objectConfigured with a ConcreteStrategy object– Maintains a reference to a Strategy objectMaintains a reference to a Strategy object– May define an interface that lets Strategy to access May define an interface that lets Strategy to access

its dataits data CollaborationsCollaborations

– Strategy and Context interact to implement the Strategy and Context interact to implement the chosen algorithm. A context may make itself access chosen algorithm. A context may make itself access to the algorithmto the algorithm

– A context forwards requests from its clients to its A context forwards requests from its clients to its strategy. Clients usually decide which strategy. Clients usually decide which ConcreteStrategy to use for the given context ConcreteStrategy to use for the given context

Page 41: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Strategy – sample codeStrategy – 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

Page 42: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Template MethodTemplate Method

Design PurposeDesign Purpose– Allow subclasses to redefine Allow subclasses to redefine

certain steps of an algorithm certain steps of an algorithm without changing the algorithm’s without changing the algorithm’s structurestructure

Design Pattern SummaryDesign Pattern Summary– Define the skeleton of an Define the skeleton of an

algorithm in an operations, algorithm in an operations, deferring some steps to subclassesdeferring some steps to subclasses

Page 43: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Template Method - Template Method - ExampleExample

Documentsave()open()close()read()

AppaddDoc()openDoc()

createDoc()canOpenDoc()

MyAppcreateDoc()

canOpenDoc()

docs

MyDocumentread()

return new MyDocument()

Page 44: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Template Method - Template Method - exampleexample

Class App { List<Document> 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 The openDoc() openDoc() of App is a template method which uses of App is a template method which uses steps (steps (canOpenDoccanOpenDoc ()and ()and createDoccreateDoc()) that are provided ()) that are provided by subclasses (by subclasses (MyAppMyApp))

Page 45: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Template Method - ModelTemplate Method - Model

AbstractClasstemplateMethod()primitiveOperation1()primitiveOperati

on2()

ConcreteClassprimitiveOperation

1()primitiveOperation

2()

{ // other operations primitiveOperation1(); primitiveOperations();}

Page 46: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Template Method - Template Method - participantsparticipants

AbstractClass (App)AbstractClass (App)– Define an algorithm as an operation which Define an algorithm as an operation which

uses abstract primitive operations (as steps uses abstract primitive operations (as steps of the algorithm) that are to be implemented of the algorithm) that are to be implemented by subclasses of AbstractClassby subclasses of AbstractClass

– Template method may call other operations Template method may call other operations defined in AbstractClassdefined in AbstractClass

ConcreteClass (MyApp)ConcreteClass (MyApp)– Implement the abstract primitive operations Implement the abstract primitive operations

that are used in the template method.that are used in the template method. CollaborationsCollaborations

– ConcreteClass relies on AbstractClass to ConcreteClass relies on AbstractClass to implement the invariant steps of the implement the invariant steps of the algorithm.algorithm.

Page 47: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

IteratorIterator visits members of a collection visits members of a collection MediatorMediator captures behavior among captures behavior among

peer objectspeer objects ObserverObserver updates objects affected by updates objects affected by

a single objecta single object CommandCommand captures function flexibly captures function flexibly

(e.g. undo-able)(e.g. undo-able)

SummarySummary

Page 48: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Other PatternsOther Patterns

Chain of ResponsibilityChain of Responsibility– Avoid coupling the sender of a request to Avoid coupling the sender of a request to

its receiver by giving more than one its receiver by giving more than one object a chance to handle the requestobject a chance to handle the request

InterpreterInterpreter– Given a language, define a Given a language, define a

representation for its grammar along with representation for its grammar along with an interpreter that uses the an interpreter that uses the representation to interpret sentences in representation to interpret sentences in the languagethe language

Page 49: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Other PatternsOther Patterns

MementoMemento– Without violating encapsulation, Without violating encapsulation,

capture and externalize an object’s capture and externalize an object’s internal state so that the object can internal state so that the object can be restored to this state laterbe restored to this state later

StateState– Allow an object to alter its behavior Allow an object to alter its behavior

when its internal state changes. when its internal state changes.

Page 50: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Other PatternsOther Patterns

StrategyStrategy– Define a family of algorithms, Define a family of algorithms,

encapsulate each one, and make encapsulate each one, and make them interchangeable. them interchangeable.

Template MethodTemplate Method– Define the skeleton of an algorithm Define the skeleton of an algorithm

in an operation, deferring some in an operation, deferring some steps to subclassessteps to subclasses

Page 51: Behavioral Design Patterns October 19, 2015October 19, 2015October 19, 2015.

Other PatternsOther Patterns

VisitorVisitor– Represent an operation to be Represent an operation to be

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