Design patterns II : Behavioural Patterns J.Serrat 102759 Software Design September 29, 2013 Index Template method 1 Strategy 2 Observer 3 Mediator 4 Visitor 5 State 6 Command 7 Chain of responsibility 8 Iterator 9
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Overview Behavioural patterns concern algorithms and the assignment of responsibilities between objects to implement them describe not just structure of classes but also the patterns of communication between them these patterns characterize complex control flow that’s difficult to follow at run-time express complex flow of control through the way objects are interconnected based more on object composition than class inheritance (read this again at the end) 3 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Template method Motivating example 1 You want to program several games like chess, checkers, snakes and ladders, poker . . . They are played differently but have in common : several players, each playing against the others only one is playing at a given time playing order is : first player, second player . . . last, first, second . . . game starts at an initial state there is some game over condition, a unique winner 1 Wikipedia, http://en.wikipedia.org/wiki/Template_method_pattern 4 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Template method class Monopoly extends Game { class Chess extends Game { void initializeGame() { void initializeGame() { // Initialize players // Initialize players // Initialize money // Put the pieces on the board } } void makePlay(int player) { void makePlay(int player) { // Process one turn of player // Process a turn for the player } } boolean endOfGame() { boolean endOfGame() { // Return true if game is over // Return true if in Checkmate or // according to Monopoly rules // Stalemate has been reached } } void printWinner() { void printWinner() { // Display who won // Display the winning player } } // ... // ... } } 5 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Template method abstract class Game { protected int playersCount; abstract void initializeGame(); abstract void makePlay(int player); abstract boolean endOfGame(); abstract void printWinner(); /* A template method : */ public final void playOneGame(int playersCount) { this.playersCount = playersCount; initializeGame(); int j = 0; while (!endOfGame()) { makePlay(j); j = (j + 1) % playersCount; } printWinner(); } } 6 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Template method 7 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Template method Intent Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. Applicability implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behaviour that can vary factor common behaviour to avoid code duplication define a template method that calls “hook” operations at specific points, thereby permitting extensions only there Hook operations may be overridden, abstract operations must be overridden, final operations can not be overridden. 8 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Template method Structure 9 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy Motivating example You are building a text editor application. Text in paragraphs of a composition must be right and left justified so that line breaks seem to be placed at the same column : 10 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy There are at the moment 3 types of line breaking computation algorithms : simple: considers each line at a time TeX algorithm : global optimization of line breaks in a composition Array algorithm : each line has the same number of characters 11 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy First solution Problem : Composition class gets bigger, more complex and harder to maintain, especially if must support multiple linebreaking algorithms 12 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy Second solution: inheritance Problems : proliferation of classes, almost identical fixed linebraking algorithm for each composition 13 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy Third solution: strategy pattern Which OO principle are we applying ? favor composition over inheritance 14 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy Intent Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Composition introduction = new Composition(new TeXCompositor()); introduction.setText("This�paper�deals�with�bla�bla�bla"); String composedText = introduction.compose(); // change composition algorithm at run time introduction.setCompositor(new SimpleCompositor()); composedText = introduction.compose(); 15 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy Structure 16 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy Applicability many related classes differ only in their behaviour, each time only one behaviour applies you need different variants of an algorithm, maybe with different space/time trade-offs an algorithm uses data that clients shouldn’t know about a class defines many behaviours appearing as multiple conditional statements 17 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy class Composition { public static int SimpleStrategy = 1; public static int TeXStrategy = 2; public static int ArrayStrategy = 3; public String compose (int breakingStrategy) { switch (breakingStrategy) { case SimpleStrategy: return composeSimple(text); break; case TeXStrategy: return composeTex(text); break; case ArrayStrategy: return composeArray(text); break; } } private String composeSimple(String str) { // ... 18 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Strategy Drawbacks Clients must be aware of different strategies. Use the Strategy pattern only when the variation in behaviour is relevant to clients Increased number of objects in an application execution, memory overhead (but see Flyweight pattern) 19 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Observer Motivating example we want to implement a desktop widget representing a clock two types of clocks are possible: digital and analogic digital clock shows time in hh:mm format, analogic in hh:mm:ss there are two responsibilities: storing and updating time, displaying time want to reuse as much as possible of the classes, e.g. to make an alarm application 20 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Observer ClockTimer is a (or has an object) thread able to periodically : ask system date and call method tick tick invokes update /s and sends it/them the present date update redraws the clock accordingly, if needed but we don’t want class ClockTimer to depend on (know) DigitalClock , AnalogicClock in order to reuse it 21 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Observer In object oriented designs classes cooperate to achieve functionalities, but tight coupling is not desirable : objects of many classes know/depend/send messages to objects of many other classes. Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. However, the changing object doesn’t know its dependents. 22 / 81
Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Observer 23 / 81 Overview Template method Strategy Observer Mediator Visitor State Command Chain of responsibility Iterator Observer Observer is implemented in java.util library Observable knows its observers (any number of objects) provides an interface for adding and removing Observer objects. Observer defines an updating interface for objects that should be notified of changes in Observable Concrete observable Clock stores state of interest to concrete Observers (present time) sends a notification to its observers when its state changes through notifyObservers 24 / 81
Recommend
More recommend