chapter 9 behavioral design patterns

91
Chapter 9 Behavioral Design Patterns

Upload: fionn

Post on 08-Jan-2016

76 views

Category:

Documents


10 download

DESCRIPTION

Chapter 9 Behavioral Design Patterns. Process Phase Affected by This Chapter. Requirements Analysis. Design. Framework. Architecture. Detailed Design. Implementation. Key:. = main emphasis. = secondary emphasis. x. x. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 9 Behavioral Design Patterns

Chapter 9Behavioral Design Patterns

Page 2: Chapter 9 Behavioral Design Patterns

Process Phase Affected by This ChapterRequirementsAnalysis

Design

Implementation

ArchitectureFramework Detailed Design

xKey: = secondary emphasisx = main emphasis

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 3: Chapter 9 Behavioral Design Patterns

Design Purpose

Interpret expressions written in a formal grammar.

Design Pattern Summary

Represent the grammar using a

Recursive design pattern form: Pass

interpretation to aggregated objects.

Interpreter

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 4: Chapter 9 Behavioral Design Patterns

Interpreter Client Interface

AbstractExpressioninterpret()

Client

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 5: Chapter 9 Behavioral Design Patterns

Interpreter Design Pattern

AbstractExpressioninterpret()

Client

TerminalExpressioninterpret()

NonTerminalExpressioninterpret()

1..n

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 6: Chapter 9 Behavioral Design Patterns

interpret()

Interpreter Sequence Diagram

TerminalExpression

:NonterminalExpression:Client AbstractExpression

NonterminalExpression

...

create & interpret()

create & interpret()

...

...

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 7: Chapter 9 Behavioral Design Patterns

Example of a Virtual Machine “Program”

260Mhz & 64MB

400Mhz & 128MB

260Mhz & 32MB

assemble ….

Graphics reproduced with permission from Corel.Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 8: Chapter 9 Behavioral Design Patterns

Input For Network Assembly Example

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 9: Chapter 9 Behavioral Design Patterns

Output of Network Assembly Example (1 of 3)

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 10: Chapter 9 Behavioral Design Patterns

Output of Network Assembly Example (2 of 3)

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 11: Chapter 9 Behavioral Design Patterns

Output of Network Assembly Example (3 of 3)

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 12: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Flexibility ,

Correctness, Reuse

Separate the processing of each part of the network order.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 13: Chapter 9 Behavioral Design Patterns

Interpreter Design Pattern

Componentassemble()

NetSystemassemble()

component1

Client

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 14: Chapter 9 Behavioral Design Patterns

Application of Interpreter Design Pattern

Componentassemble()

Computerassemble()

NetSystemassemble()

component1

component2

RAMdescribe()

CPUdescribe()

cpu

ram

Client

SetupgetInputFromUser()

parse()

1

0..1

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 15: Chapter 9 Behavioral Design Patterns

Key Concept: Interpreter Design Pattern

-- a form for parsing and a means of processing expressions.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 16: Chapter 9 Behavioral Design Patterns

- given a collection of objects

e.g.,

o the videos in a video store

o a directory

- having specified ways to progress through them

e.g.,

o “list in alphabetical order”

o “list all videos currently on loan”

... encapsulate each of these ways

Aggregate object

Purpose of Iterator

iterator2

iterator7

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 17: Chapter 9 Behavioral Design Patterns

Design Purpose (Gamma et al)

Provide a way to access the elements of an

aggregate object sequentially without

exposing its underlying representation.

Design Pattern Summary

Encapsulate the iteration in a class pointing

(in effect) to an element of the aggregate.

Iterator

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 18: Chapter 9 Behavioral Design Patterns

Using Iterator Functions

/*

To perform desiredOperation() on elements of

the aggregate according to the iteration (order) i:

*/

for( i.setToFirst(); !i.isDone(); i.increment() )

desiredOperation( i.getCurrentElement() );

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 19: Chapter 9 Behavioral Design Patterns

Functions for Iterator

// Iterator "points" to first element:

void setToFirst();

// true if iterator "points" past the last element:

boolean isDone();

// Causes the iterator to point to its next element:

void increment();

// Return the element pointed to by the iterator:

C getCurrentElement(); Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 20: Chapter 9 Behavioral Design Patterns

Iterator Operations

Set to beginning Increment Get current

elementCheck not done yet

The Iterator

Index (integer) i on

array myArrayi = 0 ++i myArray[ i ]

i < myArray.length

Index (integer) j on

VectormyVector

j = 0 ++jmyVector

.get( j )j < myVector

.size()

Iterator (object)myIterator

myIterator.setToFirst()

myIterator.increment()

myIterator.getCurrent Element()

! myIterator.isDone()

Iterator in Arrays, Vector, and in General

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 21: Chapter 9 Behavioral Design Patterns

Imagining Iterator

iterator:Iterator

element:Element

Aggregate of Elementobjects

Key: Intended sequence of Element objects

After first() executes, iterator references this object.

After increment() executes, iterator references this object.

Before increment() executes, iterator references this object.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 22: Chapter 9 Behavioral Design Patterns

Iterator Example Setup Code

// Suppose that we have iterators for forward and

// backward order: we can re-use print_employees()

List employees = new List();

ForwardListIterator fwd // to go from front to back

= new ForwardListIterator ( employees );

ReverseListIterator bckwd // to go from back to front

= new ReverseListIterator ( employees );

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

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

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 23: Chapter 9 Behavioral Design Patterns

Iterator Class Model

Aggregate

Client

IteratorsetToFirst()increment()

isDone()getCurrentItem()

ConcreteIterator ConcreteAggregateAggregatedElement 1…n1

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 24: Chapter 9 Behavioral Design Patterns

An Organizational Chart Example

Vanna Presleyvice president, 4 years

Sue Millersvce. mgr., 7 years

Sam Markhamsvce. mgr., 5 years

Sal Monahansvce. mgr., 1 year

Iolanthe Carpind. contrib., 8

Inge Carlsonind. contrib., 12

Inez Clappind. contrib., 11

Inky Conwayind. contrib., 6

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 25: Chapter 9 Behavioral Design Patterns

Iterating by Organizational Seniority Over a Bank Organization

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 26: Chapter 9 Behavioral Design Patterns

Iterating by Years of Service Over an Organization Chart

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 27: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Flexibility ,

Correctness

Separate the “visiting” procedure from the processing of individual employees.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 28: Chapter 9 Behavioral Design Patterns

Class Structure for Iterator Example

ServiceIterator

OrgSeniorityIterator

OrgChartDP OrgChartIteratorDP

Teller

Employeedisplay()

Supervisor

Client Setup

OrgChartIteratorfirst()next()isDone()currentItem()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 29: Chapter 9 Behavioral Design Patterns

Computing next()

root

1

4 5 6

9 10

2 3

7 8

11 12

( 1, 2, 0, 0 ) // my distance from the end of my sibling list )

DeepRoot

doneNode( 1 ) ( 0 )

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 30: Chapter 9 Behavioral Design Patterns

main()

Sequence Diagram for Encounter Foreign Character

Use CaseUser Employee

display( OrgCharIterator )

display()

first(), next(), idDone(), getItem() etc.

Employee

OrgChartIterator :Client

AlphabeticalOrgChartIterator

:Setup

Get org chart as in Composite example tbd

getTheIterator()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 31: Chapter 9 Behavioral Design Patterns

Computing next()

root

1

4 5 6

9 10

2 3

7 8

11 12

( 1, 2, 0, 0 )

DeepRoot

doneNode( 1 ) ( 0 )

“distance from the end of my sibling list”

( 1, 2, 0 )

( 1, 2 )

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 32: Chapter 9 Behavioral Design Patterns

main()

Iterator Example Sequence Diagram

User Employee

display( OrgCharIterator )

display()

first(), next(), isDone(), getItem() etc.

Employee

OrgChartIterator :Client

AlphabeticalOrgChartIterator:Setup

Get org chart as in Composite example tbd

getTheIterator()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 33: Chapter 9 Behavioral Design Patterns

Iterator in the Java APICollection

Iterator iterator()

Iteratornext()hasNext()remove()

ListIterator List AbstractCollection

AbstractListListIterator listIterator()

Iter*

ListItr*

* IBM implementationArrayList Vector

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 34: Chapter 9 Behavioral Design Patterns

Output for Iteration on a Java ArrayList

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 35: Chapter 9 Behavioral Design Patterns

Address Book Application Using Java Iterator

CollectionIterator iterator()

Iteratornext()

hasNext()remove()

ListIterator List

AbstractListListIterator listIterator()

ListItr*

ArrayList

NameAddrEntry AddressBook0..n

This application

Key:

Java API

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 36: Chapter 9 Behavioral Design Patterns

Iterator Class Model

ConcreteIterator

ClientAggregate

createIterator( )

IteratorsetToFirst()increment()isDone()getCurrentItem()

ConcreteAggregate

createIterator( )

return new ConcreteIterator( this );

OLD

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 37: Chapter 9 Behavioral Design Patterns

Output for StringTokenizer Example

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 38: Chapter 9 Behavioral Design Patterns

Key Concept: Iterator Design Pattern

-- to access the elements of a collection.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 39: Chapter 9 Behavioral Design Patterns

Solicitation of Customer Information 1 of 2

Name and Location

Basic information

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 40: Chapter 9 Behavioral Design Patterns

Solicitation of Customer Information 2 of 2

Account Information

Additional information

Customer ID

Total business

Amount due

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 41: Chapter 9 Behavioral Design Patterns

Design Purpose

Avoid references between dependent objects.

Design Pattern Summary

Capture mutual behavior in a separate class.

Mediator

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 42: Chapter 9 Behavioral Design Patterns

The Mediator Class Model

Mediator Colleague

ConcreteMediator

ConcreteColleague1 ConcreteColleague2

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 43: Chapter 9 Behavioral Design Patterns

:ConcreteMediator

:ConcreteColleague1 :ConcreteColleague2

:Mediator2. Initiation on a ConcreteColleague

doPart1()

doPart2()

1. Initiation by ConcreteMediator

mediate()

mediate()

doSome1()

doSome2()

Mediator Sequence Diagrams

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 44: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Reusability and

Robustness

Avoid hard-coded dependencies among the game’s GUI classes, enabling their use in other contexts.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 45: Chapter 9 Behavioral Design Patterns

Application of Mediator To Customer Information Application

CustomerDisplay

:BasicInfoGUI:

CustomerGUI

:CustTypeDisplay :CustInfoDisplay

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 46: Chapter 9 Behavioral Design Patterns

The Mediator Class Model in the Java API

ComponentListeneractionPerformed()

ComponentaddComponentListener()

MyEventListener

MyComponent1 MyComponent2

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 47: Chapter 9 Behavioral Design Patterns

Key Concept: Mediator Design Pattern

-- to capture mutual behavior without direct dependency.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 48: Chapter 9 Behavioral Design Patterns

Design Purpose

Arrange for a set of objects to

be affected by a single object.

Design Pattern Summary

The single object aggregates the set, calling a

method with a fixed name on each member.

Observer

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 49: Chapter 9 Behavioral Design Patterns

Observer Design Pattern

Sourcenotify()

Observerupdate()

for all Observer’s o:o.update();

Client of thissystem1

2

1..n

Server part Client part

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 50: Chapter 9 Behavioral Design Patterns

Observer Design Pattern

Sourcenotify()

Observerupdate()

ConcreteSourcestate

ConcreteObserverobserverState

update()

for all Observer’s o: o.update();

Client

2

3

1..n

Server part Client part

1

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 51: Chapter 9 Behavioral Design Patterns

Observer Applied to International Hamburger Co.

Sourcenotify()

Observerupdate()

Headquartersdemand

SeniorManagementforecastupdate()

Client1..n

MarketingmarketingDemand

update()doDisplay()if( abs( hq.demand - marketingDemand ) > 0.01 )

{ marketingDemand = hq.getDemand();doDisplay();

}

Server part Client part

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 52: Chapter 9 Behavioral Design Patterns

I/O Example for Mutual Fund Observer Example

Note: HiGrowthMutualFund starts with 3 shares of Awesome, assumes price of 1.0, and has non-Awesome holdings totalling 400.0

Note: MedGrowthMutualFund starts with 2 shares of Awesome, assumes price of 1.0, and has non-Awesome holdings totalling 300.0

Note: LoGrowthMutualFund starts with 1 shares of Awesome, assumes price of 1.0, and has non-Awesome holdings totalling 200.0

Enter 'quit': Any other input to continue.

go on

Enter the current price of Awesome Inc. in decimal form.

32.1

Value of Lo Growth Mutual Fund changed from 201.0 to 232.1

Value of Med Growth Mutual Fund changed from 302.0 to 364.2

Value of Hi Growth Mutual Fund changed from 403.0 to 496.3

Enter 'quit': Any other input to continue.

go on

Enter the current price of Awesome Inc. in decimal form.

21.0

Value of Lo Growth Mutual Fund changed from 232.1 to 221.0

Value of Med Growth Mutual Fund changed from 364.2 to 342.0

Value of Hi Growth Mutual Fund changed from 496.3 to 463.0

Enter 'quit': Any other input to continue.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 53: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Flexibility

Allow mutual funds objects to easily acquire or divest of stocks.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 54: Chapter 9 Behavioral Design Patterns

ObservablenotifyObservers()

Observerupdate( Observable, Object )

AwesomeIncprice

LongTermMutualFund….

update(…)

Observer Example:

Mutual Funds

Key:Developer Class

Java API Class

MediumTermMutualFund….

update(…)HiGrowthMutualFund

….update(…)

MutualFundvalue

numAwesomeShares

Client

Setup

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 55: Chapter 9 Behavioral Design Patterns

ObservablenotifyObservers()

Observerupdate( Observable, Object )

MyObservableMyConcreteObserver

observerStateupdate(…)

Observer in the Java API

subject

Key: Developer ClassJava API Class

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 56: Chapter 9 Behavioral Design Patterns

Key Concept: Observer Design Pattern

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

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 57: Chapter 9 Behavioral Design Patterns

Design Purpose

Cause an object to behave in a

manner determined by its state.

Design Pattern Summary

Aggregate a State object

and delegate behavior to it.

State

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 58: Chapter 9 Behavioral Design Patterns

TargetStateBhandleRequest()

TargetdoRequest()

State Design Pattern Structure: doRequest() behaves according to state of Target

targetState TargetStatehandleRequest()

Client

TargetStateAhandleRequest()

1

{ targetState.handleRequest(); }

. . . . . .

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 59: Chapter 9 Behavioral Design Patterns

GUI For a Role-Playing Video Game

Set Characteristics

Courtesy Tom VanCourt and CorelAdapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 60: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Correctness and

Reusability

Separate the generic code for handling button clicks from the actions which depend on the game’s status at the time.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 61: Chapter 9 Behavioral Design Patterns

State Design Pattern Applied to Role-Playing Game

MyGamesetCharacteristics()

MyGameStatehandleClick()

state

{ state.handleClick(); }

EngaginghandleClick()

SettingUphandleClick()

WaitinghandleClick()

SettingCharacteristicshandleClick()

{ showWindow(); …. // more }

{ showWindow(); …. // more }

{ // already responding … // display message }

{ // do nothing … // display message}

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 62: Chapter 9 Behavioral Design Patterns

Key Concept: State Design Pattern

-- to cause a object’s functions to behave according to the state it’s in.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 63: Chapter 9 Behavioral Design Patterns

Design Purpose

Allow a set of objects to service a request.

Present clients with a simple interface.

Design Pattern Summary

Link the objects in a chain via aggregation,

allowing each to perform some of the

responsibility, passing the request along.

Chain of Responsibility

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 64: Chapter 9 Behavioral Design Patterns

Chain of Responsibility: Object Model

entryHandler:HandlerSubclassX

(next element): HandlerSubclassY

(next element): HandlerSubclassZ

successor successor

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 65: Chapter 9 Behavioral Design Patterns

HandlerSubclassAhandleRequest()respondA()

Chain of Responsibility Class Model

Client

HandlerSubclassBhandleRequest() respondB()

successor

Handler

handleRequest()

respondA(); // handle some of the required functionality successor.handleRequest(); // pass along remaining responsibility

. . . .

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 66: Chapter 9 Behavioral Design Patterns

GUI For Customer Information Application

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 67: Chapter 9 Behavioral Design Patterns

Output for Customer Information Application

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 68: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Flexibility

Isolate the responsibilities of each part of the input form to generate its XML.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 69: Chapter 9 Behavioral Design Patterns

Class Model For User Information Collection

CustomerInfoElement

CustomerName CompanyNameCustomerInfo

CustomerPersonal CustomerProfessionalCustomerAddress Company

container

TextFieldListener«client»

CustomerInfoApp«setup»

Each of these classes supports handleClick()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 70: Chapter 9 Behavioral Design Patterns

Object Model Fragment for Customer Information Example

: CompanyName

:Company

:CustomerProfessional

container

:CustomerInfo

handleClick()

container

handleClick()

container

handleClick()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 71: Chapter 9 Behavioral Design Patterns

Key Concept: Chain of Responsibility Design Pattern

-- to distribute functional responsibility among a collection of objects.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 72: Chapter 9 Behavioral Design Patterns

Design Purpose

Increase flexibility in calling for a service

e.g., allow undo-able operations.

Design Pattern Summary

Capture operations as classes.

Command

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 73: Chapter 9 Behavioral Design Patterns

Target1action1()

The Command Design Pattern

Action2Commandexecute()

Target2action2()

replacedCommand

execute()

Action1Commandexecute()

Client

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 74: Chapter 9 Behavioral Design Patterns

The Command Design Pattern: Example

MenuItemhandleClick()

Commandexecute()

CutCommandexecute()

Documentcut()

copy()

document

command

CopyCommandexecute()

document

document.cut()

document.copy()

command.execute()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 75: Chapter 9 Behavioral Design Patterns

execute()

Sequence Diagram for Document Command Example

:MenuItem

handleClick()

command:Command

:CopyCommand

document:Document

copy()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 76: Chapter 9 Behavioral Design Patterns

I/O for Word Processor Undo

Example1 of 2

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 77: Chapter 9 Behavioral Design Patterns

I/O for Word Processor Undo Example

2 of 2

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 78: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Flexibility and

Robustness

Isolate the responsibilities of the Word Processor commands, making them save-able and reversible.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 79: Chapter 9 Behavioral Design Patterns

Undo Example Class Model

WordProcessorCommand

execute()undo()

CutCommandtextCut: String

offset: int execute()

undo()

Documenttext: String

commandHistory

PasteCommand offset: intlength: intexecute()

undo()

0..n

QuitCommandexecute()

UndoCommandexecute()

document

DocumentCommandgetInputFromUser()document

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 80: Chapter 9 Behavioral Design Patterns

Key Concept: Command Design Pattern

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

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 81: Chapter 9 Behavioral Design Patterns

• Required to solve equations of the form

ax2 + bx + c = 0.

• Must be able to handle all input possibilities for a, b, and c.

• This is a tutorial application that must provide full explanations to users about the solutions for all values for a, b, and c.

Example of Template Motivation

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 82: Chapter 9 Behavioral Design Patterns

1. Report progress2. Display number of solutions3. Display first solution, if any 4. Display second solution, if any

A Basic

Quadratic

Algorithm

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 83: Chapter 9 Behavioral Design Patterns

Design Purpose

Allow runtime variants on an algorithm.

Design Pattern Summary

Express the basic algorithm in a base class,

using method calls where variation is

required.

Template

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 84: Chapter 9 Behavioral Design Patterns

Class Model for Template

TemplateAlgorithmhandleRequest()

nonInheritedMethod()calledMethod1()calledMethod2()

….

Algorithm1calledMethod1()calledMethod2()

….

algorithm

Algorithm3calledMethod1()calledMethod2()

….

Client

Algorithm2calledMethod1()calledMethod2()

….

{ algorithm.handleRequest(); }

SubjectdoRequest()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 85: Chapter 9 Behavioral Design Patterns

I/O For Quadratic Example 1/2

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 86: Chapter 9 Behavioral Design Patterns

I/O For Quadratic Example 2/2

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 87: Chapter 9 Behavioral Design Patterns

displaySolutions()

{

displayWhatsHappening();

displayNumSolutions();

displayFirstSolutions();

displaySecondSolution();

}

Quadratic Display Algorithm

Override

Override

Override

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 88: Chapter 9 Behavioral Design Patterns

Design Goal At Work: Flexibility and

Robustness

Isolate the main algorithm for quadratic solution display. Isolate the variants that depend on the coefficients.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 89: Chapter 9 Behavioral Design Patterns

NoSolutionsdisplayNumSolutions()displayFirstSolution()

displaySecondSolution()

OneSolutiondisplayNumSolutions()displayFirstSolution()

displaySecondSolution()

Class Model for Quadratic Problem

QuadraticEquationfloat a, b, c

solveQuadratic()

QuadraticAlgorithmdisplayWhatsHappening()

displaySolution()inputMakesSense()

displayNumSolutions();displayFirstSolution()

displaySecondSolution()

algorithm

TwoSolutionsdisplayNumSolutions()displayFirstSolution()

displaySecondSolution()

Client

{ algorithm.displaySolution(); }

SetupgetABC()

InfinitelyManySolutionsdisplayNumSolutions()displayFirstSolution()

displaySecondSolution()

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 90: Chapter 9 Behavioral Design Patterns

Key Concept: Template Design Pattern

-- to capture a basic algorithm and its variants.

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.

Page 91: Chapter 9 Behavioral Design Patterns

Behavioral Design Patterns capture behavior among objects

Interpreter handles expressions in grammers

Iterator visits members of a collection

Mediator captures behavior among peer objects

Observer updates objects affected by a single object

State allows method behavior to depend on current status

Chain of Responsibility allows a set of objects to provide

functionality collectively

Command captures function flexibly (e.g. undo-able)

Template captures basic algorithms, allowing variability

Summary of Behavioral

Patterns

Adapted from Software Design: From Programming to Architecture by Eric J. Braude (Wiley 2003), with permission.