Behavioral Design Patterns 28 October 2020 Behavioral Patterns
Behavioral Design Patterns 28 October 2020
Behavioral Patterns – 1 Command n Iterator n Mediator n Observer n Strategy n Template Method n
Behavioral Patterns – 2 n n n Chain of Responsibility Interpreter Momento State Visitor
Iterator n Design Purpose – Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation n Design Pattern Summary – Encapsulate the iteration in a class pointing (in effect) to an element of the aggregate
Iterator Interface Iterator { // move to first item: void first(); // if it is at last item: boolean is. Done(); // move point to next item: void next(); // Return the current: Object current. Item(); }
Using Iterator /* To perform desired. Operation() on items in the container according to the iteration (order) i: */ Iterator i = Iterator. Object; for(i. first(); !i. is. Done(); i. next()) desired. Operation(i. current. Item());
Iterator Sample Code // Suppose that we have iterators forward and // backward order: we can re-use print_employees() List employees = new List(); Iterator fwd = employees. create. Forward. Iterator(); Iterator bckwd = employees. create. Backward. Iterator(); // print from front to back client. print_employees(fwd); // print from back to front client. print_employees(bckwd);
Using Iterator Class Client extends … { print_employees(Iterator it) { for(it. first(); !it. is. Done(); it. next()) { print(i. current. Item()); } } // other operations }
Iterator Class Model Client Iterator first() next() is. Done() current. Item() Concrete. Iterator Container create. Iterator() append() remove() Concrete. Container create. Iterator() return new Concrete. Iterator(this)
Iterator - Question What is the difference between the two clients Class Client 1 { void operation( Container c) { Iterator it = c. create. Iterator(); for (it. first(); it. is. Done(); it. next()) { Object item = it. current. Item(); // process item } } } Class Client 2 { void operation( Iterator it) { for (it. first(); it. is. Done(); it. next()) { Object item = it. current. Item(); // process item } } }
Iterator - Question Client 1 Iterator Client 1 is dependent upon two interfaces: Iterator and Container Client 2 is dependent upon only one interface: Iterator
Iterator in Java - 1 Interface Iterator<E> { // check if there are more elements. boolean has. Next(); // Returns the next element in the iteration. E next() // Removes from the underlying collection // the last element returned by the iterator // (optional operation). void remove(); }
Iterator in Java - 2 import java. util. Iterator; public class Array. List. Via. List. With. Iterator<E> { private Node head, tail; private int count; public Array. List. Via. Linked. List. With. Inner. Iterator() { 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 is. Empty() { … } public E remove(int i) { … } public E set(int i, E e) { … } public int size() { … }
Iterator in Java - 3 private class Node { private E item; private Node next; Node(E i, Node n) { … } public E get. Item() { … } public void set. Item(E item) {{ … } public Node get. Next() { … } public void set. Next(Node next) { … } }
Iterator in Java - 4 private class ALIterator implements Iterator<E> { private Node cursor; public AIIterator() { cursor = head; } public boolean has. Next() { return cursor != null; } public E next() { Node tmp = cursor; cursor = cursor. get. Next(); return tmp. get. Item(); } public void remove() { throw new Runtime. Exception("not supported"); } } // end of Iterator } // end of Array. List
Observer n Design Purpose – Arrange for a set of objects to be affected by a single object. n Design Pattern Summary – The single object aggregates the set, calling a method with a fixed name on each member.
Observer - example
Observer - Structure Subject attach(Observer) detach(Observer) notify() observers 1. . n Observer update(subject) for o: observers o. update(this); Concrete. Observer observer. State update(Subject s) Concrete. Subject subject. State get. State() set. State() // change state notify(); … s. get. State(); …
Observer: Sequence diagram Client set. State() : Subject O 1: Observer O 2: Observer notify() update() get. State()
Observer in Java Observable notify. Observers() attach(Observer) detach(Observer) My. Observable subject. State subjec t Observer update(Observable, Object ) My. Concrete. Observer observer. State update(…)
Observer: Key Concept -- to keep a set of objects up to date with the state of a designated object.
Mediator n Design Purpose – Avoid references between dependent objects. n Design Pattern Summary – Capture mutual behavior in a separate class.
Mediator - example
Mediator - example
Mediator - example
Mediator - example
Mediator - Model Mediator Colleague_A Concrete. Mediator Colleague_B
Mediator Sequence Diagram B: Colleague_B Client : Mediator A: Colleague_A request() mediate() take. Action_1() take. Action_2() take. Action_3() C: Colleague_A
Key Concept: Mediator -- to capture mutual behavior without direct dependency.
Command n Design Purpose – Increase flexibility in calling for a service e. g. , allow undo-able operations. n Design Pattern Summary – Capture operations as classes.
Command - Structure Client Invoker Command +request() Receiver action() execute(); receiver Concrete. Command execte() State receiver. action()
Command – Sequence Diagram R: Receiver : Client C: Concrete. Cmd Invoker new Concrete. Cmd( R ) new Invoker( C ) execute() action()
Command - Example Cut: Button command Clicked() Copy: Button command Clicked() execute(); command. execute() Cut. Command Copy. Command execte() doc command. execute() Cut: Menu. Item Selected() doc. cut() doc. copy() Document copy() cut() A B: A composed in B
Command – Setup d: Doc a. Client C: Copy. Command X: Cut. Command new Doc() new Cut. Command( d ) new Copy. Command( d ) new Menu. Item( x ) new Button( c ) Cut: Menu. Item Copy: Button Cut: Button
Command – Sequence Diagram Cut: Menu. Item Copy: Button Cut: Button selected() clicked() Cut. Command execute() Document Copy. Command cut() execute() copy()
Key Concept - Command -- to avoid calling a method directly (e. g. , so as to record or intercept it).
Strategy n Design Purpose – Allow the algorithm vary independently from clients that use it n Design Pattern Summary – Define a family of algorithms, encapsulate each one, and make them interchangeable
Strategy - Example Player. Pool sorter Sorter sort() choose. Two() . . . sorter. sort(); . . . Bubble. Sorter sort() Merger. Sorter sort()
Strategy - Model Context strategy Strategy Algorithm() context. Interface() Concreate. Strategy. A algorithm() Concreate. Strategy. B algorithm() Concreate. Strategy. C algorithm()
Strategy - participants n Strategy (Sorter) n Concrete. Strategy (Bubble. Sort and Merge. Sort) n Context (Player. Pool) n Collaborations – Declare an interface for the family of algorithms – Implementations of the algorithms. – Configured with a Concrete. Strategy object – Maintains a reference to a Strategy object – May define an interface that lets Strategy to access its data – Strategy and Context interact to implement the chosen algorithm. A context may make itself access to the algorithm – A context forwards requests from its clients to its strategy. Clients usually decide which Concrete. Strategy to use for the given context
Strategy – sample code Class Player. Pool { Array. List players; Comparator c; Sorter sorter; Player. Pool(Comparator c, Sorter s) { this. c = c; this. sorter = s; } Player[] choose. Two() { sorter. sort(players, c); players[0] = players. remove(); players[1] = players. remove(); return players; } } Interface Sorter { void sort(List list, Comparator c) } Class Bubble. Sort implements Sorter { void sort(List l, Comparator c) } Class Merge. Sort implements Sorter { void sort(List l, Comparator c) } Class Client { void main() { Player players[2]; Comparator c = new Priority. Comp(); Sorter s = new Bubble. Sort(); Player. Pool vip = new Player. Pool(c, s); players = vip. choose. Two(); // use players to form a game } } Actually, Comparator for sort() is a strategy in this example
Template Method n Design Purpose – Allow subclasses to redefine certain steps of an algorithm without changing the algorithm’s structure n Design Pattern Summary – Define the skeleton of an algorithm in an operations, deferring some steps to subclasses
Template Method - Example Document save() open() close() read() My. Document read() docs App add. Doc() open. Doc() create. Doc() can. Open. Doc() My. App create. Doc() can. Open. Doc() return new My. Document()
Template Method - example n The open. Doc() of App is a template method which uses steps (can. Open. Doc ()and create. Doc()) that are provided by subclasses (My. App) Class App { List<Document> docs; void open. Doc(String file) { if (!can. Open. Doc(file)) { // cannot handle this doc return; } Document doc = create. Doc(file); docs. add(doc); doc. open(); doc. read(); } }
Template Method - Model Abstract. Class template. Method() primitive. Operation 1() primitive. Operation 2() { // other operations primitive. Operation 1(); primitive. Operations(); } Concrete. Class primitive. Operation 1() primitive. Operation 2()
Template Method - participants n Abstract. Class (App) n Concrete. Class (My. App) n Collaborations – Define an algorithm as an operation which uses abstract primitive operations (as steps of the algorithm) that are to be implemented by subclasses of Abstract. Class – Template method may call other operations defined in Abstract. Class – Implement the abstract primitive operations that are used in the template method. – Concrete. Class relies on Abstract. Class to implement the invariant steps of the algorithm.
Summary Iterator visits members of a collection n Mediator captures behavior among peer n objects n Observer updates objects affected by a single object n Command captures function flexibly (e. g. undo-able)
Other Patterns n Chain of Responsibility – Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request n Interpreter – Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language
Other Patterns n Memento – Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later n State – Allow an object to alter its behavior when its internal state changes.
Other Patterns n Strategy – Define a family of algorithms, encapsulate each one, and make them interchangeable. n Template Method – Define the skeleton of an algorithm in an operation, deferring some steps to subclasses
Other Patterns n Visitor – Represent an operation to be performed on the elements of an object structure. A new operation may be encapsulated in a Visitor without the need to change the classes of the elements which it operates on
- Slides: 51