+ All Categories
Home > Documents > Behavioral Design Patterns May 5, 2015May 5, 2015May 5, 2015.

Behavioral Design Patterns May 5, 2015May 5, 2015May 5, 2015.

Date post: 16-Dec-2015
Category:
Upload: jamie-wilbanks
View: 216 times
Download: 2 times
Share this document with a friend
28
Behavioral Design Behavioral Design Patterns Patterns March 21, 2022 March 21, 2022
Transcript

Behavioral Design Behavioral Design PatternsPatterns

April 18, 2023April 18, 2023

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

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

}

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

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

= employees.createForwardIterator();ReverseListIterator bckwd

= employees.createBackwardIterator();

// print from front to back client.print_employees(fwd); // print from back to front client.print_employees(bckwd);

Using IteratorUsing Iterator

Class Client extends … {

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

print(i.currentItem()); } }

// other operations

}

Iterator Class ModelIterator Class ModelClient

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

ContainercreateIterator()append()remove()

ConcreteIterator

return new ConcreteIterator(this)

ConcreteContainer

createIterator()

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

Iterator - QuestionIterator - Question

Client1

Iterator Container

Client2

Client1 is dependent upon two interfaces: Iterator and Container

Client2 is dependent upon only one interface: Iterator

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

} }                     

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() { … }

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) { … } } // end of Node

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

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.

Observer - StructureObserver - Structure

1..n

for o: observers o.update(this);

observers

SubjectAttach(Observer)Detach(Observer)Notify()

ObserverUpdate(Subject)

ConcreteSubject

stategetState()setState()

ConcreteObserver

observerStateUpdate(Subject s)

// change stateNotify();

…s.getState();…

Observer: Sequence Observer: Sequence diagramdiagram

Client O1:Observer

:Subject O2: Observer

setState() notify()

getState()

getState()

update()

update()

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

Observerupdate(Observable, Object )

MyObservablesubjectState

MyConcreteObserverobserverStateupdate(…)

subject

ObserverObserver: Key Concept: Key Concept

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

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.

Mediator - ModelMediator - Model

Mediator Colleague

ConcreteMediator

Colleague_BColleague_A

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

Key Concept: Key Concept: MediatorMediator

-- to capture mutual behavior without direct dependency.

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.

Command - Command - StructureStructure

Client Invoker+request()

ConcreteCommand

execte()State

Commandexecute();

receiver.action()

receiverReceiveraction()

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

Clicked()

command.execute()

Command – Sequence Command – Sequence DiagramDiagram

Cut:Button

CopyCommand

Command

DocumentCutCommand

Copy:Button

Cut:MenuItem

selected() execute()cut()

clicked()cut()

execute()

clicked()copy()

execute()

Key Concept - Key Concept - CommandCommand

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

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


Recommended