behavioral design patterns november 17, 2015november 17, 2015november 17, 2015
TRANSCRIPT
Behavioral Design Behavioral Design PatternsPatterns
April 20, 2023April 20, 2023
Behavioral Patterns – Behavioral Patterns – 11 CommandCommand IteratorIterator MediatorMediator ObserverObserver StrategyStrategy Template MethodTemplate Method
Behavioral Patterns – Behavioral Patterns – 22 Chain of ResponsibilityChain of Responsibility InterpreterInterpreter MomentoMomento StateState StrategyStrategy Template MethodTemplate Method VisitorVisitor
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 - exampleObserver - example
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();…
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 - exampleMediator - example
Mediator - exampleMediator - example
Mediator - exampleMediator - example
Mediator - exampleMediator - example
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()
Command – Sequence Command – Sequence DiagramDiagram
C: ConcreteCmd
R:Receiver :Client Invoker
new ConcreteCmd( R )
action()execute()
new Invoker( C )
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()
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 )
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).
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
Strategy - ExampleStrategy - Example
PlayerPoolchooseTwo(
)
Sortersort()
MergerSortersort()
BubbleSortersort()
... sorter.sort();...
sorter
Strategy - ModelStrategy - Model
ContextcontextInterfac
e()
StrategyAlgorithm()
ConcreateStrategyA
algorithm()
strategy
ConcreateStrategyB
algorithm()
ConcreateStrategyC
algorithm()
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
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
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
Template Method - Template Method - ExampleExample
Documentsave()open()close()read()
AppaddDoc()openDoc()
createDoc()canOpenDoc()
MyAppcreateDoc()
canOpenDoc()
docs
MyDocumentread()
return new MyDocument()
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))
Template Method - ModelTemplate Method - Model
AbstractClasstemplateMethod()primitiveOperation1()primitiveOperati
on2()
ConcreteClassprimitiveOperation
1()primitiveOperation
2()
{ // other operations primitiveOperation1(); primitiveOperations();}
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.
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
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
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.
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
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