58
1 Module 4: UML In Action - Design Patterns

Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

1

Module 4:

UML In Action -Design Patterns

Page 2: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

2

Overview

�Books

�Design Patterns –Basics

�Structural Design Patterns

�Behavioral Design Patterns

�Appendix: More on the Observer Pattern

More on the Strategy Pattern

Page 3: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

3

Books

�Design Patterns : Elements of Reusable Object-Oriented Software

(1995)

�(The-Gang-of-Four Book)

�The-Gang-of-Four (GoF) -Gamma, Helm, Johnson , Vlissides

�Analysis Patterns -Reusable Object Models (1997)

�Martin Fowler

�The Design Patterns Smalltalk Companion (1998)

�Alpert, Brown & Woolf

Page 4: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

4

Design Patterns

“Each pattern describes

a problemwhich occurs over and over again in our environment,

and then describes the core of the solutionto that problem, in

such a way that you can use this solution a million times over,

without ever doing it the same way twice”.

---Christopher Alexander, 1977

This was in describing patterns in buildings and towns.

This was in describing patterns in buildings and towns.

In SE, design patterns are in terms of objects and interfaces, n

In SE, design patterns are in terms of objects and interfaces, not ot

walls and doors.

walls and doors.

The manner in which a collection of interacting objects collaborate to accomplish a

specific task or provide some specific functionality.

Page 5: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

5

Architecture vs. Design Patterns

�High-level framework for structuringan application

�“client-server based on remote procedure calls”

�“abstraction layering”

�“distributed object-oriented system based on CORBA”

�Defines the system in terms of computational components & their

interactions

Arc

hit

ectu

re

De

sig

n P

att

ern

s

�Lower level than architectures (Sometimes, called micro-architecture)

�Reusable collaborations that solve subproblems within an application

�how can I decouple subsystem X from subsystem Y?

�Design patterns support object-oriented reuseat a high level of abstraction

�Design patterns provide a “framework”that guides and constrains object-oriented implementation

Why Design Patterns?

Page 6: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

6

4 Essential Elements of Design Patterns

�Name: identifies a pattern

�Problem: describes when to apply the pattern in terms of the

problem and context

�Solution: describes elements that make up the design, their

relationships, responsibilities, and collaborations

�Consequences: results and trade-offs of applying the pattern

Page 7: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

7

How to Describe Design Patterns more fully

This is critical because the information has to be conveyed to peer developers in

order for them to be able to evaluate, select and utilize patterns.

�A format for design patterns

�Pattern Name and Classification

�Intent

�Also Known As

�Motivation

�Applicability

�Structure

�Participants

�Collaborations

�Consequences

�Implementation

�Sample Code

�Known Uses

�Related Patterns

Page 8: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

8

Organizing Design Patterns

�By Purpose(reflects what a pattern does):

�Creational Patterns

�Structural Patterns

�Behavioral Patterns

�By Scope: specifies whether the pattern applies primarily to

�classesor to

�objects.

Page 9: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

9

Design Patterns Space

Abstract Factory

Builder

Prototype

Singleton

Adapter

Bridge

Composite

Decorator

Façade

Flyweight

Proxy

Chain of

Responsibility

Command

Iterator

Mediator

Memento

Observer

State

Strategy

Visitor

Factory Method

Adapter

Interpreter

Template

Creational

Structural

Behavioral

Object

Class

Scope

Purpose

Page 10: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

10

Some Design Patterns

Pattern Name

Role

Adapter

Convert the interface of one class into another interface

clients expect. Adapter allows classes to work together

that otherwise can’t because of incompatible interfaces.

Proxy

Provide a surrogate or placeholder for another object.

Mediator

Define an object that encapsulates how a set of

objects interact. Mediator promotes loose coupling by

keeping objects from referring to each other explicitly

and let one vary its interaction independently

Observer

Define a one-to-many dependency between

objects so that when one object changes state, all

its dependents will be notified and updated automatically.

Template

Define the skeleton of an algorithm in an

operation, deferring some steps to subclasses.

Page 11: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

11

Structural Patterns

�Composite

�Adapter

�Façade

�Proxy

Page 12: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

12

Structural Patterns -Composite

Compose objects into tree structures to represent part-whole

hierarchies. Composite lets clients treat individual objects and

compositions of objects uniformly.

Co

mp

osit

e:

Ap

pli

ca

bil

ity

�Represents part-whole hierarchies of objects.

�Clients ignore the difference between compositions of objects and

individual objects.

�Clients treat all objects in the composite structure uniformly.

Intent

Page 13: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

13

Structural Patterns –Composite

Cla

ss D

iag

ram

Client

Component

operation()

getChild( i:int )

Leaf

operation()

Composite

operation()

add( c:Component )

remove( c:Component )

getChild( i:int )

operation()

{ for all g in children

g.operation()

}

*

Page 14: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

14

Structural Patterns -Composite

Ob

ject

Dia

gra

m

top : Composite

top : Composite

a : Leaf

b : Leaf

c : Leaf

d : Leaf

e : Leaf

Page 15: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

15

-root ---Leaf A

---Leaf B

---Composite

X -----Leaf XA

-----Leaf XB

---Leaf C

usin

gS

yste

m;

usin

gS

yste

m.C

oll

ecti

on

s;

na

me

sp

ace

Do

Fa

cto

ry.G

an

gO

fFo

ur.

Co

mp

osit

e.S

tru

ctu

ral

{

// M

ain

Ap

p t

est

ap

pli

ca

tio

n

cla

ss

Ma

inA

pp

{sta

tic

vo

idM

ain

(){

// C

rea

te a

tre

e s

tru

ctu

re

Co

mp

osit

e r

oo

t =

ne

wC

om

po

sit

e("

roo

t");

roo

t.A

dd

( ne

wL

ea

f("L

ea

f A

"));

roo

t.A

dd

(ne

wL

ea

f("L

ea

f B

"));

Co

mp

osit

e c

om

p =

ne

wC

om

po

sit

e("

Co

mp

osit

e X

");

co

mp

.Ad

d(n

ew

Le

af(

"Le

af

XA

"));

co

mp

.Ad

d(n

ew

Le

af(

"Le

af

XB

"));

roo

t.A

dd

(co

mp

);ro

ot.

Ad

d(n

ew

Le

af(

"Le

af

C")

);

// A

dd

an

d r

em

ov

e a

le

af

Le

af

lea

f =

ne

wL

ea

f("L

ea

f D

");

roo

t.A

dd

(le

af)

;ro

ot.

Re

mo

ve

(le

af)

;

// R

ecu

rsiv

ely

dis

pla

y t

ree

ro

ot.

Dis

pla

y(1

);

// W

ait

fo

r u

se

r C

on

so

le.R

ea

d()

;}

}

// "

Co

mp

on

en

t"

ab

str

act

cla

ss

Co

mp

on

en

t{

pro

tecte

dstr

ing

na

me

;

// C

on

str

ucto

r p

ub

lic

Co

mp

on

en

t(str

ing

na

me

){

this

.na

me

= n

am

e;}

pu

bli

ca

bstr

act

vo

idA

dd

(Co

mp

on

en

t c);

pu

bli

ca

bstr

act

vo

idR

em

ov

e(C

om

po

ne

nt

c);

pu

bli

ca

bstr

act

vo

idD

isp

lay

(in

td

ep

th);

} // "

Co

mp

osit

e"

cla

ss

Co

mp

osit

e :

Co

mp

on

en

t{

pri

va

teA

rra

yL

ist

ch

ild

ren

= n

ew

Arr

ay

Lis

t();

// C

on

str

ucto

r p

ub

lic

Co

mp

osit

e(s

trin

gn

am

e)

: b

ase

(na

me

) {

}

pu

bli

co

ve

rrid

ev

oid

Ad

d(C

om

po

ne

nt

co

mp

on

en

t){

ch

ild

ren

.Ad

d(c

om

po

ne

nt)

;}

pu

bli

co

ve

rrid

ev

oid

Re

mo

ve

(Co

mp

on

en

t co

mp

on

en

t){

ch

ild

ren

.Re

mo

ve

(co

mp

on

en

t);}

pu

bli

co

ve

rrid

ev

oid

Dis

pla

y(i

nt

de

pth

){

Co

nso

le.W

rite

Lin

e( n

ew

Str

ing

('-'

, d

ep

th)

+ n

am

e);

// R

ecu

rsiv

ely

dis

pla

y c

hil

d n

od

es

fore

ach

(Co

mp

on

en

t co

mp

on

en

t in

ch

ild

ren

){

co

mp

on

en

t.D

isp

lay

(de

pth

+ 2

);}

}} //

"L

ea

f"

cla

ss

Le

af

: C

om

po

ne

nt

{//

Co

nstr

ucto

r p

ub

lic

Le

af(

str

ing

na

me

) :

ba

se

(na

me

) {

}

pu

bli

co

ve

rrid

ev

oid

Ad

d(C

om

po

ne

nt

c)

{C

on

so

le.W

rite

Lin

e("

Ca

nn

ot

ad

d t

o a

le

af"

);}

pu

bli

co

ve

rrid

ev

oid

Re

mo

ve

(Co

mp

on

en

t c)

{C

on

so

le.W

rite

Lin

e("

Ca

nn

ot

rem

ov

e f

rom

a l

ea

f");

}

pu

bli

co

ve

rrid

ev

oid

Dis

pla

y(i

nt

de

pth

){

Co

nso

le.W

rite

Lin

e(n

ew

Str

ing

('-'

, d

ep

th)

+ n

am

e);

}}

}

htt

p:/

/ww

w.d

ofa

cto

ry.c

om

/Pa

tte

rns/P

att

ern

Co

mp

osit

e.a

sp

x

Page 16: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

16

Structural Patterns –Composite

�Declares the interface for objects in the composition.

�Implements default behavior for the interface common to all classes, as appropriate.

�Declares an interface for accessing and managing its child components.

�Optionally defines an interface for accessing a components parent.

Leaf

�Represents leaf objects in the composition.

�Defines behavior for primitive objects in the composition.

Composite

�Defines behavior for components having children.

�Stores child components.

�Implements child-related operations.

Client

�Manipulates objects in the composition through the Component interface.

Component

Pa

rtic

ipa

nts

Page 17: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

17

Structural Patterns –Composite

�Clients use the Component class interface to interact with objects in

the composite structure.

�If the recipient is a Leaf, then the request is handled directly.

�If the recipient is a Composite, then it usually forwards requests to

its child components, possibly performing additional operations

before and/or after forwarding.

Co

lla

bo

rati

on

s

Page 18: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

18

Structural Patterns -Adapter

Convert the interface of a class into another interface clients expect.

Adapter lets classes work together that couldn’t otherwise because of

incompatible interfaces.

Applicability

�Reuse of an existing class is desired, but the interface does not

match the need.

�Design of a reusable class that cooperates with unrelated or

unforeseen classes, but classes don’t have compatible interfaces.

Intent

Page 19: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

19

Structural Patterns -Adapter

Client

Adapter

+request()

Adaptee

+specialOperation()

Target

+request()

adaptee.specificOperation()

Cla

ss D

iag

ram

Page 20: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

20

Structural Patterns -Adapter

�Target—defines the domain-specific interface that the client uses.

�Client—collaborates with objects conforming to the Target interface.

�Adaptee—defines an existing interface that needs adapting.

�Adapter—adapts the interface of Adaptee to the Target interface.

Pa

rtic

ipa

nts

�Clients call operations on an Adapter instance. In turn, the Adapter

calls Adaptee operations that carry out the request.

Co

lla

bo

rati

on

s

Page 21: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

21

Structural Patterns -Façade

Provide a unified interface to a set of interfaces in a subsystem.

Façade defines a higher-level interface that makes the subsystem

easier to use.

Ap

plica

bil

ity

�Provides a simple interface to a complex subsystem.

�Decouples the details of a subsystem from clients and other

subsystems.

�Provides a layered approach to subsystems.

Inte

nt

Page 22: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

22

Structural Patterns -Façade

Cla

ss D

iag

ram

subsystem

Facade

Page 23: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

23

Structural Patterns -Façade

�Façade

�Knows which classes are responsible for each request.

�Delegates client requests to appropriate objects.

�Subsystem classes

�Implement subsystem functionality.

�Handle work assigned by the Façade object.

�Have no knowledge of the façade.

Pa

rtic

ipa

nts

�Clients communicate with the subsystem sending requests to the Façade.

�Reduces the number of classes the client deals with.

�Simplifies the subsystem.

�Clients do not have to access subsystem objects directly.

Co

lla

bo

rati

on

s

Page 24: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

24

Structural Patterns -Proxy

Provide a surrogate or placeholder for another object to controlaccess

to it.

Ap

plica

bil

ity

�Remote proxy —

provides a local representative for an object in a

different address space.

�Virtual proxy —

creates expensive objects on demand.

�Protection proxy —

controls access to the original object.

�Smart reference —

replacement for a bare pointer

�Reference counting

�Loading persistent object on access

�Transactional locking

Inte

nt

Page 25: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

25

Structural Patterns -Proxy

Cla

ss D

iag

ram

Client

<<abstract>>

Subject

request()

...

RealSubject

request()

...

Proxy

request()

...

request()

{...

realSubject.request()

...

}

Page 26: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

26

Structural Patterns -Proxy

Ob

ject

Dia

gra

m

aClient: aProxy : Proxy

subject : RealSubject

Page 27: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

27

Structural Patterns -Proxy

�Subject: Defines the common interface for RealSubject and Proxy.

�Proxy:

�Maintains reference to real subject

�Can be substituted for a real subject

�Controls access to real subject

�May be responsible for creating and deleting the real subject

�Special responsibilities

�Marshaling for remote communication

�Caching data

�Access validation

�RealSubject: Defines the real object that the proxy represents.

�Client: Accesses the RealSubject through the intervention of the Proxy.

Pa

rtic

ipa

nts

�Proxy forwards requests to RealSubject when appropriate, depending on

the kind of proxy.

Co

lla

bo

rati

on

s

Page 28: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

28

Behavioral Patterns

�Observer

�Strategy

�Command

�State

�Visitor

Page 29: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

29

Behavioral Patterns -Observer

�Define a one-to-many dependency between objects so that when

one object changes state, all its dependents are notified and

updated automatically.

Inte

nt

�An abstraction has two aspects, one dependent on the other.

�When changing one object requires changing others, and you don’t

know how many objects need changed.

�When an object needs to notify others without knowledge about who

they are.

Ap

plica

bil

ity

Page 30: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

30

Behavioral Patterns -Observer

Cla

ss D

iag

ram

subject

observers

*

update()

ConcreteObserver

attach( observer )

detach( observer )

notify()

Subject

for all o in observers

o.update()

getState()

subjectState

ConcreteSubject

update()

<<interface>>

Observer

observerState :=

subject.getState()

Page 31: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

31

Behavioral Patterns -Observer

�Subject

�Knows its observers, but not their “real”identity.

�Provides an interface for attaching/detaching observers

.

�Observer

�Defines an updating interface for objects that should be identified of changes.

�ConcreteSubject

�Stores state of interest to ConcreteObserver objects.

�Sends update notice to observers upon state change.

�ConcreteObserver

�Maintains reference to ConcreteSubject (sometimes).

�Maintains state that must be consistent with ConcreteSubject.

�Implements the Observer interface.

Pa

rtic

ipa

nts

�ConcreteSubject notifies observers when changes occur.

�ConcreteObserver may query subject regarding state change.

Co

lla

bo

rati

on

s

Page 32: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

32

Behavioral Patterns -Observer

Se

qu

en

ce

Dia

gra

m

subject :

ConcreteSubject

observer1 :

ConcreteObserver

observer2 :

ConcreteObserver

attach( observer1 )

attach( observer2 )

update()

getState()

update()

getState()

notify()

Page 33: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

33

Behavioral Patterns -Strategy Pattern

�Intent: d

efi

ne

s a

fa

mily

of

alg

ori

thm

s,

en

ca

psu

late

ea

ch

o

ne

, a

nd

ma

ke

th

em

in

terc

ha

ng

ea

ble

. S

tra

teg

y l

ets

th

e

alg

ori

thm

va

ry i

nd

ep

en

de

ntl

y f

rom

clie

nts

th

at

use

it.

�Motivation:

wh

en

th

ere

are

ma

ny

alg

ori

thm

s f

or

so

lvin

g a

p

rob

lem

, h

ard

-wir

ing

all a

lgo

rith

ms i

n c

lie

nt’

s c

od

e m

ay

h

av

e s

ev

era

l p

rob

lem

s:

�C

lie

nts

ge

t fa

t a

nd

ha

rde

r to

ma

inta

in

�D

iffe

ren

t a

lgo

rith

ms m

ay

be

ap

pro

pri

ate

at

dif

fere

nt

tim

e

�It

is d

iffi

cu

lt t

o a

dd

ne

w a

lgo

rith

ms

Page 34: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

34

Behavioral Patterns -Strategy Pattern

Context

ContextInterface()

Strategy

AlgorithmInterface()

ConcreteStrategyB

AlgorithmInterface()

ConcreteStrategyA

AlgorithmInterface()

ConcreteStrategyC

AlgorithmInterface()

strategy

Page 35: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

35

Behavioral Patterns -Participants of Strategy

�Strategy:

de

cla

res a

n i

nte

rfa

ce

co

mm

on

to

all s

up

po

rte

d

alg

ori

thm

. C

on

tex

t u

se

s t

his

in

terf

ace

to

ca

ll t

he

alg

ori

thm

d

efi

ne

d b

y a

Co

ncre

teS

tra

teg

y.

�ConcreteStrategy:

imp

lem

en

ts t

he

alg

ori

thm

usin

g t

he

S

tra

teg

y i

nte

rfa

ce

�Context: m

ain

tain

s a

re

fere

nce

to

a S

tra

teg

y o

bje

ct

an

d

de

fin

es a

n i

nte

rfa

ce

th

at

let

Str

ate

gy

acce

ss i

ts d

ata

Page 36: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

36

Behavioral Patterns -Sorting Example

�Requirement:

we

wa

nt

to s

ort

a l

ist

of

inte

ge

rs u

sin

g

dif

fere

nt

so

rtin

g a

lgo

rith

ms,

e.g

. q

uic

k s

ort

, se

lecti

on

so

rt,

inse

rtio

n s

ort

, e

tc.

�E

.g.,

{3

, 5

, 6

, 2

, 4

4,

67

, 1

, 3

44

, ..

. }

�{

1,

2,

3,

5,

6,

44

, 6

7,

34

4,

...

}

�O

ne

wa

y t

o s

olv

e t

his

pro

ble

m i

s t

o w

rite

a f

un

cti

on

fo

r e

ach

so

rtin

g a

lgo

rith

m,

e.g

.

�q

uic

kso

rt(i

nt[

] in

, in

t[]

res)

�in

se

rtio

nso

rt(i

nt[

] in

, in

t[]

res)

�m

erg

eso

rt(i

nt[

] in

, in

t[]

res)

�A

be

tte

r w

ay

is t

o u

se

th

e S

tra

teg

y p

att

ern

Page 37: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

37

Behavioral Patterns -Strategy Pattern

SortedList

SetSortStr(sortStr:SortStrategy)

Sort()

SortStrategy

Sort(list:ArrayList)

InsertionSort

Sort(list:ArrayList)

QuickSort

Sort(list:ArrayList)

MergeSort

Sort(list:ArrayList)

-sortStrategy

Main

Main() s

tdR

ec

-lis

t: A

rra

yLis

t

Sort()

{so

rtS

tra

teg

y.S

ort

(lis

t)}

How is –sortStrategy implemented?

Main()

{… std

Re

c.S

etS

ort

Str

(so

rtS

trIn

fo);

std

Re

c.S

ort

()}

How is stdRec implemented?

Page 38: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

38

Behavioral Patterns-Command

Encapsulate a request as an object, thereby letting you parameterize

clients with different requests, queue or log requests, and support

undoable operations.

Intent

�Parameterize objects by an action

�In place of “callbacks”

�Specify, queue, and execute requests at different times

�Supports undo when Command maintains state information necessary

for reversing command.

�Added support for logging Command behavior.

�Support high-level operations built on primitive operations (transactions).

Ap

pli

ca

bil

ity

Page 39: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

39

Behavioral Patterns-Command

Cla

ss D

iag

ram

*Client

Invoker

action()

Receiver

execute()

<<abstract>>

Command

execute()

state

ConcreteCommand

receiver.action()

Page 40: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

40

Behavioral Patterns -Command

�Command: Declares an interface for executing an operation.

�ConcreteCommand

�Defines a binding between a Receiver object and an action.

�Implements execute() by invoking a corresponding operation on Receiver.

�Client(Application):Creates a Command object and sets its Receiver.

�Invoker:Asks the Command to carry out a request.

�Receiver:Knows how to perform the operation associated with a request.

Can be any class.

Pa

rtic

ipa

nts

�Creates a ConcreteCommand object and sets its Receiver.

�An Invoker stores the ConcreteCommand.

�Invoker calls execute()on command.

�ConcreteCommand invokes operation on its receiver.

Co

lla

bo

rati

on

s

Page 41: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

41

Behavioral Patterns -Command

aClient : Client

aReceiver:

anInvoker :

Invoker

aCommand :

ConcreteCommand

create( aReceiver )

store( aCommand )

action()

execute()

Se

qu

en

ce

Dia

gra

m

Page 42: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

42

Behavioral Patterns -State

Allow an object to alter its behavior when its internal state changes. The

object will appear to change its class.

Inte

nt

�An object’s behavior depends on its state, and it must change its

behavior at run-time depending on its state.

�Operations have large, multipart conditional statements that depend

on the object’s state.

�Usually represented by constants.

�Some times, the same conditional structure is repeated.

Ap

plica

bil

ity

Page 43: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

43

Behavioral Patterns -State

Cla

ss D

iag

ram

state

request()

Context

state.handle();

handle()

<<abstract>>

State

handle()

ConcreteStateA

handle()

ConcreteStateB

Page 44: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

44

Behavioral Patterns -State

�Context

�Defines interface of interest to clients.

�Maintains an association with a subclass of State, that defines the current state.

�State

�Defines an interface for encapsulating the behavior with respectto state.

�ConcreteStatex

�Each subclass implements a behavior associated with a particularstate of the Context.

Pa

rtic

ipa

nts

�Context delegates state-specific behavior to the current concrete State object.

�The state object may need access to Context information; so the context is usually

passed as a parameter.

�Clients do not deal with State object directly.

�Either Context or a concrete State subclass can decide which state succeeds

another.

Co

lla

bo

rati

on

s

Page 45: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

45

Behavioral Patterns -Visitor

Represent an operation to be performed on the elements of an object

structure. Visitor lets you define a new operation without changing

the classes of the elements on which it operates.

Inte

nt

�An object structure contains many disparate classes, and operations

need to be performed based on concrete classes.

�Many distinct operations need to be performed on an object

structure.

�An object structure rarely changes, but new operations need to be

defined over the structure.

Ap

plica

bil

ity

Page 46: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

46

Behavioral Patterns -Visitor

Cla

ss D

iag

ram

*Client visitA( element : ConcreteElementA )

visitB( element : ConcreteElementB )

<<abstract>>

Visitor

visitA( element : ConcreteElementA )

visitB( element : ConcreteElementB )

ConcreteVisitor1

visitA( element : ConcreteElementA )

visitB( element : ConcreteElementB )

ConcreteVisitor2

ObjectStructure

accept( v : Visitor )

<<abstract>>

Element

accept( v : Visitor )

operationA()

ConcreteElementA

accept( v : Visitor )

operationB()

ConcreteElementB

v.visitA( this )

v.visitB( this )

Page 47: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

47

Behavioral Patterns -Visitor

�Visitor—declares a visit operation for eachclass within the object structure aggregation.

�ConcreteVisitor—implements each operation declared by Visitor. Provides algorithm

context.

�Element—defines an accept operation taking a Visitor as an argument.

�ConcreteElementX

—implements an accept operation taking a Visitor as an argument.

�ObjectStructure

�Enumerates its elements; potentially disparate classes.

�May provide a high level interface for visitor to visit its elements.

�Potentially a composite or just a general collection.

Pa

rtic

ipa

nts

�A client creates an instance of a concrete Visitor subclass.

�Client requests the ObjectStructure to allow the visitor to visit each.

�When visited, Element invokes the appropriate operation on Visitor;

overloading to know the element type.

Co

lla

bo

rati

on

s

Page 48: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

48

Behavioral Patterns -Visitor

Se

qu

en

ce

Dia

gra

m

aStruct :

ObjectStructure

v : Visitor

elemB :

ConcreteElementB

elemA :

ConcreteElementA

accept( v )

accept( v )

visitConcreteElementB( elemB )

operationB()

visitConcreteElementA( elemA )

operationA()

Page 49: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

49

How to Select & Use Design Patterns

�Scan Intent Sections

�Study How Patterns Interrelate

�Study Patterns of Like Purpose

�Examine a Cause of Redesign

�Consider What Should Be Variable in Your Design

�Read the pattern once through for an overview: appears trivial, but not

�Go back and study the structure, participants, and collaborations sections

�Look at Sample Code: concrete example of pattern in code

�Choose names for pattern participants

�Define the classes

�Define application specific names for operations in the pattern

�Implement the operations to carry out the responsibilities and collaborations in

the pattern

Ho

w t

o U

se

Ho

w t

o S

ele

ct (> 20 in the book, and still growing …fast?, more on Internet)

Page 50: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

50

Appendix: More on the Observer Pattern

�Decouples a subject and its observers

�Widely used in Smalltalk to separate application objects from interface objects

�Known in the Smalltalk world as Model-View-Controller (MVC)

�Rationale:

the interface is very likely to change while the underlying business objects remain

stable

�Defines a subject (the Observable) that is observed

�Allows multiple observers to monitor state changes in the subject without

the subject having explicit knowledge about the existence of the

observers

Subject

Observer

Observer

Observer

Page 51: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

51

Appendix: More on the Observer Pattern

The Model-View-Controller (MVC)

�Developed at Xerox Parcto provide foundation classes for Smalltalk-80

�The Model, View and Controller classes have more than a 10 year history

�Fundamental Principle

�separate the underlying application MODEL (business objects) from the

INTERFACE (presentation objects)

Business Objects

(the Model in MVC)

Expert Interface

Novice Interface

Ra

tio

na

le f

or

MV

C: Design for change and reuse

MV

C a

nd

Ob

se

rve

r P

att

ern

�In Smalltalk, objects may have dependents

�When an object announces “I have changed”, its dependents are notified

�It is the responsibility of the dependents to take action or ignore the notification

Page 52: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

52

Appendix: More on the Observer Pattern

java.util.Observable

�Observable/subject objects (the Modelin Model-View) can announce

that they have changed

�Methods:

–void setChanged()

–void clearChanged()

–booleanhasChanged()

Harry

setC

hang

ed()

hasC

hang

ed()

True/false

�WHAT IF Observers query a Subject periodically?

Subject

Observer

qu

ery

Page 53: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

53

Appendix: More on the Observer Pattern

Implementing & Checking an Observable

import java.util.*;

import java.io.*;

public class Harry extendsObservable {

private booleanmaritalStatus= false;

public Harry (booleanisMarried) {

maritalStatus= isMarried;

} public void updateMaritalStatus(booleanchange) {

maritalStatus= change;

// set flag for anyone interested to check

this.setChanged();

}Imp

lem

en

tin

g a

n O

bse

rva

ble

public static void main (String args[ ] ) {

Harry harry= new Harry (false);

harry.updateMaritalStatus(true);

if (harry.hasChanged() )

System.out.println("Time to call harry");

}Ch

eck

ing

an

Ob

se

rva

ble

Page 54: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

54

+ Good: Any object can observe by calling hasChanged()

-Bad: the observer must actively call hasChanged()

? What’s the alternative? Automatic notification -> Observer pattern

Appendix: More on the Observer Pattern

WHAT IF Observers query a Subject periodically? Good or Bad?

Page 55: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

55

Appendix: More on the Observer Pattern

Implementing the Observer Pattern

Harry

Observer1

Observer2

add

Ob

serv

er(t

his

)

add

Ob

serv

er(o

bse

rver

2)

Ste

p 1

: O

bse

rve

rs r

eg

iste

r w

ith

Ob

se

rva

ble

up

dat

e(O

bse

rvab

le o

, Ob

ject

arg

)Harry

no

tify

Ob

serv

ers(

Ob

ject

arg

)

Observer1

Observable (Harry) may also send himself a

no

tify

Ob

serv

ers(

)msg-no params

Ste

p 2

. O

bse

rva

ble

no

tifi

es O

bse

rve

rs

Page 56: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

56

Appendix: More on the Observer Pattern

java.util.Observable

�The superclassof all ‘observable’objects to be used in the Model

View design pattern

�Methods are provided to:

�void addObserver(anObserver)

�int countObservers()

�void deleteObserver(anObserver)

�void deleteObservers()

�Interface

�Defines the update() method that allows an object to ‘observe’

subclasses of Observable

�Objects that implement the interface may be passed as parametersin:

�addObserver(Observero)

Page 57: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

57

Summary

�Design Patterns

�Creational Patterns

�Structural Patterns:

Ad

ap

ter,

Co

mp

osit

e,

Fa

ça

de

, P

rox

y

�Behavioral Patterns: Command, Observer, State, Visitor

�Appendix: More on the Observer Pattern

�The Model-View-Controller (MVC)

�java.util.Observable

Page 58: Module 4 - University of Texas at Dallaschung/Fujitsu/M04_DesignPatterns.pdfDesign Patterns Space Abstract Factory Builder Prototype Singleton Adapter Bridge Composite Decorator Façade

58

Points to Ponder

�List as many design patterns as you can think of in the Model-View-

Controller (MVC).

�How many design patterns can exist? In the order of tens?

hundreds? or thousands? Justify your reasoning.

�What would be the major differences between design patterns and

architectural patterns?

�What style of architecture is closest to the Observer pattern inthe

manner objects interact with each other?

�Map the Observer pattern into the Java Event Model.

�What are the essential tradeoffs between

1) Observers query a Subject periodically and

2) using the Observer pattern?