Upload
karthik-kompelli
View
232
Download
0
Embed Size (px)
Citation preview
8/12/2019 Dp Unit-Vii Jntuworld
1/86
UNIT-VII 1
Behavioral patterns part-II introduction
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
Reference
1
2
3
4
5
6
7
8
9
S. No TOPIC PPT Slides
L1 2 4
L2 5 12
L3 13 32
L4 33 54
L5 55 62
L6 63 73
L7 74 82
L8 83 85
L9 86 86
8/12/2019 Dp Unit-Vii Jntuworld
2/86
UNIT-VII 2
Behavioral Patterns !"
Deal with the way objects interact and distributeresponsibility
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. Chain the receiving
objects an dpass the request along the chain until an
object handles it.
Command: ncapsulate a request as an object! thereby
letting you paramateri"e clients with different requests!
queue or log requests! and support undoable operations. #nterpreter: $iven a language! define a representation
for its grammar along with an interpreter that uses the
representation to interpret sentences in thelanguage.%&
L1
8/12/2019 Dp Unit-Vii Jntuworld
3/86
UNIT-VII 3
'ehavioral (atterns )%* #terator: (rovide a way to access the elements of an
aggregate object sequentially without e+posing its
underlying representation.
,ediator: Define an object that encapsulates how a set
of objects interact. ,ediator promotes loose coupling by
-eeping objects from referring to each other e+plicitly!
and lets you vary their interaction independently. ,emento: ithout violating encapsulation! capture and
e+ternali"e an object/s internal state so that the object
can be restored to this state later.
0bserver: Define a one1to1many dependency between
objects so that when one object changes state! all its
dependents are notified and updated automatically.
L1
8/12/2019 Dp Unit-Vii Jntuworld
4/86
UNIT-VII 4
Behavioral Patterns #" 2tate: Allow an object to alter its behavior when its
internal state changes. 3he object will appear to change
its class.
2trategy: Define a family of algorithms! encapsulate
each one! and ma-e them interchangeable. 2trategy
lets the algorithm vary independently from clients that
use it.
3emplate ,ethod: Define the s-eleton of an algorithmin an operation! deferring some steps to subclasses.
3emplate ,ethod lets subclasseses redefine certain
steps of an algorithm without changing the algorithm/s
structure. 4isitor: Represent an operation to be performed on the
elements of an object structure. 4isitor lets you define a
new operation without changing the classes of the
elements on which it operates.
L1
8/12/2019 Dp Unit-Vii Jntuworld
5/86
UNIT-VII 5
The Mediator Pattern
The Mediator pattern reduces coupling and
simpliies code !hen se"eral o#$ects must
negotiate a comple% interaction&
'lasses interact onl( !ith a mediator classrather than !ith each other&
'lasses are coupled onl( to the mediator
!here interaction control code resides&
Mediator is li)e a multi-!a( *a+ade pattern&
,nalog( a meeting scheduler
L2
8/12/2019 Dp Unit-Vii Jntuworld
6/86
UNIT-VII .
Using a MediatorL2
8/12/2019 Dp Unit-Vii Jntuworld
7/86
UNIT-VII /
Mediator Pattern 0tructureL2
8/12/2019 Dp Unit-Vii Jntuworld
8/86
UNIT-VII
Mediator as a ro)erL2
8/12/2019 Dp Unit-Vii Jntuworld
9/86
UNIT-VII
Mediator eha"iorL2
8/12/2019 Dp Unit-Vii Jntuworld
10/86
UNIT-VII 1
hen to Use a Mediator
Use the Mediator pattern !hen a
comple% interaction #et!een
colla#orators must #e encapsulated to
6 7ecouple colla#orators8
6 'entrali9e control o an interaction8 and
6 0impli( the colla#orators&
Using a mediator ma( compromiseperormance&
L2
8/12/2019 Dp Unit-Vii Jntuworld
11/86
UNIT-VII 11
Mediators8 *a+ades8 and'ontrol 0t(les
The *a+ade and Mediator
patterns pro"ide means to ma)e
control more centrali9ed& The *a+ade and Mediator
patterns should #e used to mo"e
rom a dispersed to a delegatedst(le8 #ut not rom a delegated to
a centrali9ed st(le&
L2
8/12/2019 Dp Unit-Vii Jntuworld
12/86
UNIT-VII 12
0ummar(
ro)er patterns use a ro)er class to
acilitate the interaction #et!een a 'lient
and a 0upplier&
The *a+ade pattern uses a #ro)er :thea+ade; to pro"ide a simpliied interace
to a comple% su#-s(stem&
The Mediator pattern uses a #ro)er toencapsulate and control a comple%
interaction among se"eral suppliers&
L2
8/12/2019 Dp Unit-Vii Jntuworld
13/86
UNIT-VII 13
Memento Pattern
L3
8/12/2019 Dp Unit-Vii Jntuworld
14/86
UNIT-VII 14
8/12/2019 Dp Unit-Vii Jntuworld
15/86
UNIT-VII 15
Intent
'apture and e%ternali9e an o#$ect>s state!ithout "iolating encapsulation&
s state at some later time&
6 Useul !hen implementing chec)points andundo mechanisms that let users #ac) out otentati"e operations or reco"er rom errors&
6 ?ntrusts other o#$ects !ith the inormation it
needs to re"ert to a pre"ious state !ithoute%posing its internal structure andrepresentations&
L3
8/12/2019 Dp Unit-Vii Jntuworld
16/86
UNIT-VII 1.
*orces
,pplication needs to capture states at certaintimes or at user discretion& Ma( #e used or6 Undue = redo
6 Cog errors or e"ents
6 ac)trac)ing
Need to preser"e encapsulation6 7on>t share )no!ledge o state !ith other o#$ects
D#$ect o!ning state ma( not )no! !hen to ta)estate snapshot&
L3
8/12/2019 Dp Unit-Vii Jntuworld
17/86
UNIT-VII 1/
Moti"ation
Man( technical processes in"ol"e the
e%ploration o some comple% data
structure&
Dten !e need to #ac)trac) !hen a
particular path pro"es unproducti"e&
6 ?%amples are graph algorithms8 searching
)no!ledge #ases8 and te%t na"igation&
L3
8/12/2019 Dp Unit-Vii Jntuworld
18/86
UNIT-VII 1
Moti"ation
Memento stores a snapshot o another o#$ect>s
internal state8 e%posure o !hich !ould "iolate
encapsulation and compromise the application>s
relia#ilit( and e%tensi#ilit(&
, graphical editor ma( encapsulate the connecti"it(
relationships #et!een o#$ects in a class8 !hose
pu#lic interace might #e insuicient to allo! precise
re"ersal o a moveoperation&
Move
$ndo
L3
8/12/2019 Dp Unit-Vii Jntuworld
19/86
UNIT-VII 1
Moti"ation
Memento pattern sol"es this pro#lem as ollo!s
The editor reEuests a memento rom the o#$ect
#eore e%ecuting moveoperation&
Driginator creates and returns a memento&
7uring undooperation8 the editor gi"es the
memento #ac) to the originator&
ased on the inormation in the memento8 the
originator restores itsel to its pre"ious state&
L3
8/12/2019 Dp Unit-Vii Jntuworld
20/86
UNIT-VII 2
,pplica#ilit(
Use the Memento pattern !hen
6, snapshot o an o#$ect>s state must #e
sa"ed so that it can #e restored later8 and6 direct access to the state !ould e%pose
implementation details and #rea)
encapsulation&
L3
8/12/2019 Dp Unit-Vii Jntuworld
21/86
UNIT-VII 21
0tructure
,ttri#ute
state
Dperation 0etMemento:Memento m; 'reateMemento: ;
Driginator
,ttri#ute
state
Dperation Fet0tate: ; 0et0tate: ;
Memento
careta)er
return ne! Memento:state;
state G m-HFet0tate: ;
L3
8/12/2019 Dp Unit-Vii Jntuworld
22/86
UNIT-VII 22
Participants
Memento
6 0tores internal state o the Driginator
o#$ect& Driginator decides ho! much&6 Protects against access #( o#$ects other
than the originator&
6 Mementos ha"e t!o interaces 'areta)er sees a narro! interace&
Driginator sees a !ide interace&
L3
8/12/2019 Dp Unit-Vii Jntuworld
23/86
UNIT-VII 23
Participants :continued;
Driginator
6 'reates a memento containing a snapshot
o its current internal state&6 Uses the memento to restore its internal
state&
L3
8/12/2019 Dp Unit-Vii Jntuworld
24/86
UNIT-VII 24
'areta)er
Is responsi#le or the memento>s
sae)eeping&
Ne"er operates on or e%amines the
contents o a memento&
L3
L3
8/12/2019 Dp Unit-Vii Jntuworld
25/86
UNIT-VII 25
?"ent Trace
'reateMemento: ;
0etMemento:aMemento;
anOriginatoraCaretaer a!e"ento
ne! Memento
0et0tate: ;
Fet0tate: ;
L3
L3
8/12/2019 Dp Unit-Vii Jntuworld
26/86
UNIT-VII 2.
'olla#orations
, careta)er reEuests a memento rom
an originator8 holds it or a time8 and
passes it #ac) to the originator&
Mementos are passi"e& Dnl( the
originator that created a memento !illassign or retrie"e its state&
L3
L3
8/12/2019 Dp Unit-Vii Jntuworld
27/86
UNIT-VII 2/
'onseEuences
Memento has se"eral conseEuences
6 Memento a"oids e%posing inormation that
onl( an originator should manage8 #ut orsimplicit( should #e stored outside the
originator&
6 @a"ing clients manage the state the( as)
or simpliies the originator&
L3
L3
8/12/2019 Dp Unit-Vii Jntuworld
28/86
UNIT-VII 2
'onseEuences :continued;
Using mementos ma( #e e%pensi"e8 due to
cop(ing o large amounts o state or reEuent
creation o mementos&
, careta)er is responsi#le or deleting the
mementos it cares or&
, careta)er ma( incur large storage costs
!hen it stores mementos&
L3
L3
8/12/2019 Dp Unit-Vii Jntuworld
29/86
UNIT-VII 2
Implementation
hen mementos get created and
passed #ac) to their originator in a
predicta#le seEuence8 then Mementocan sa"e $ust incremental changes to
originator>s state&
L3
L3
8/12/2019 Dp Unit-Vii Jntuworld
30/86
UNIT-VII 3
no!n Uses
Mementois a 2 ilma#out Ceonard 0hel#( andhis Euest to re"enge the#rutal murder o his !ie&
Though Ceonard ishampered !ith short-termmemor( loss8 he uses notesand tatoos to compile theinormation into a suspect&
L3
L3
http://en.wikipedia.org/wiki/Mementohttp://en.wikipedia.org/wiki/2000_in_filmhttp://en.wikipedia.org/wiki/2000_in_filmhttp://en.wikipedia.org/wiki/Memento8/12/2019 Dp Unit-Vii Jntuworld
31/86
UNIT-VII 31
no!n Use o Pattern
7(lan language uses memento to
pro"ide iterators or its collection acilit(&
6 7(lan is a d(namic o#$ect orientedlanguage using the unctional st(le&
6 7e"elopment started #( ,pple8 #ut
su#seEuentl( mo"ed to open source&
L3
L3
8/12/2019 Dp Unit-Vii Jntuworld
32/86
UNIT-VII 32
8/12/2019 Dp Unit-Vii Jntuworld
33/86
UNIT-VII 33
D#ser"er Pattern
7eine a one-to-man( dependenc(8 allthe dependents are notiied and
updated automaticall( The interaction is )no!n as #$%lis&'
s$%s(ri%eor s$%s(ri%e'noti)*
,"oiding o#ser"er-speciic updateprotocol #$ll "odel"s& #$s& "odel
Dther conseEuences and open issues
L4
L4
8/12/2019 Dp Unit-Vii Jntuworld
34/86
UNIT-VII 34
D#ser"er Pattern
Intent6 7eine a one-to-man( dependenc( #et!een o#$ects
so that !hen one o#$ect changes state8 all itsdependents are notiied and updated automaticall(
e( orces6 There ma( #e man( o#ser"ers
6 ?ach o#ser"er ma( react dierentl( to the samenotiication
6 The su#$ect should #e as decoupled as possi#le romthe o#ser"ers to allo! o#ser"ers to changeindependentl( o the su#$ect
L4
L4
8/12/2019 Dp Unit-Vii Jntuworld
35/86
UNIT-VII 35
D#ser"er Man(-to-one dependenc( #et!een o#$ects Use !hen there are t!o or more "ie!s on the same JdataK a)a JPu#lish and su#scri#eK mechanism 'hoice o JpushK or JpullK notiication st(les
Observerupdate()
Subjectattach:D#ser"er;
detach:D#ser"er;
noti(:;
'oncreteD#ser"erupdate:;
'oncrete0u#$ectget0tate:;
stateGsu#$ect&get0tate:;L
orall o in o#ser"ers
o&update:;
D#ser"erL4
8/12/2019 Dp Unit-Vii Jntuworld
36/86
UNIT-VII 3.
D#ser"er
?ncapsulating 'ontrol *lo!
%ame&0bserver design pattern
Problem description&
,aintains consistency across state of one 2ubjectand many
0bservers.Solution&
A 2ubjecthas a primary function to maintain some state )e.g.! a data
structure*. 0ne or more 0bserversuse this state! which introduces
redundancy between the states of 2ubjectand 0bserver.
0bserverinvo-es the subscribe)*method to synchroni"e the state.
henever the state changes! 2ubjectinvo-es its notify)*method to
iteratively invo-e each 0bserver.update)*method.
D#ser"erL4
8/12/2019 Dp Unit-Vii Jntuworld
37/86
UNIT-VII 3/
D#ser"er
'lass 7iagram
2ubject
subscribe)*
unsubscribe)*
notify)*
subscribers
Concrete2ubject
state
getstate)*
setstate)*
Observer
update)*
Concrete0bserver
observe2tate
update)*
5 6
L4
8/12/2019 Dp Unit-Vii Jntuworld
38/86
UNIT-VII 3
D#ser"er
'onseEuences
'onse(uences&
Decouples 2ubject! which maintains state! from 0bservers!
who ma-e use of the state.
Can result in many spurious broadcasts when the state of
2ubjectchanges.
L4
8/12/2019 Dp Unit-Vii Jntuworld
39/86
UNIT-VII 3
'olla#orations in D#ser"er Pattern
01 'oncrete0u#$ect o#s1 'oncreteD#ser"er o#s2 'oncreteD#ser"er
set0tate:;
noti(:;
update:;
get0tate:;
update:;
get0tate:;
L4
8/12/2019 Dp Unit-Vii Jntuworld
40/86
UNIT-VII 4
D#ser"er Pattern 1
Need to separatepresentational aspects !ith the data8 i&e& separate"ie!s and data&
'lasses deining application data and presentation can #e
reused&
'hangein one "ie! automaticall( relectedin other
"ie!s& ,lso8 change in the application data is relected in
all "ie!s&
7eines one-to-man( dependenc(amongst o#$ects so that !hen one o#$ect changes its state8
all its dependents are notiied&
L4
8/12/2019 Dp Unit-Vii Jntuworld
41/86
UNIT-VII 41
D#ser"er Pattern 2
A7589
'789
C7&89
D7%89
Application data
A
'C
D
A DC'
Relative (ercentages
; 58 8 &8 %8
< 5= &= &= 5=
> 58 8 &8 %8
A ' C D
Change notification
Requests! modifications
D# P tt 3L4
8/12/2019 Dp Unit-Vii Jntuworld
42/86
UNIT-VII 42
D#ser"er Pattern 3
Subject
attach )0bserver*
detach )0bserver*
?otify )*
Observer
@pdate)*
'oncrete Observer
@pdate)*
observer2tate
'oncrete Sub)ect
$et2tate)*
2et2tate)*
subject2tate
observers
subject
or all + in observersB
+ @pdate)*
observer2tate7
subject get2tate)*
L4
8/12/2019 Dp Unit-Vii Jntuworld
43/86
UNIT-VII 43
'lass colla#oration in D#ser"er
:Concrete2ubject :Concrete0bserver15 :Concrete0bserver1%
$et2tate)*
?otify)*
@pdate)*
2et2tate)*
$et2tate)*
@pdate)*
L4
8/12/2019 Dp Unit-Vii Jntuworld
44/86
UNIT-VII 44
D#ser"er Pattern D#ser"er code
class 0u#$ectL
class o#ser"er O
pu#lic
"irtual o#ser"erL
protected
"irtual "oid Update :0u#$ectQ the'hanged0u#$ect;GL
o#ser"er :;L
?ote the support for multiple subjects.
RL
Abstract class defining
the 0bserver interface.
L4
8/12/2019 Dp Unit-Vii Jntuworld
45/86
UNIT-VII 45
D#ser"er Pattern 0u#$ect 'ode 1
class 0u#$ect O
pu#lic
"irtual 0u#$ectL
protected
0u#$ect :;L
"irtual "oid ,ttach :o#ser"erQ;L
"irtual "oid 7etach :o#ser"erQ; L
"irtual "oid Noti(:;L
pri"ate
Cist SD#ser"erQH QBo#ser"ersL
RL
Abstract class defining
the 2ubject interface.
L4
8/12/2019 Dp Unit-Vii Jntuworld
46/86
UNIT-VII 4.
D#ser"er Pattern 0u#$ect 'ode 2
"oid 0u#$ect ,ttach :D#ser"erQ o;O
Bo#ser"ers -H ,ppend:o;L
R
"oid 0u#$ect 7etach :D#ser"erQ o;O
Bo#ser"ers -H
8/12/2019 Dp Unit-Vii Jntuworld
47/86
UNIT-VII 4/
D#ser"er Pattern , 'oncrete 0u#$ect
1
class 'loc)Timer pu#lic 0u#$ect O
pu#lic
"irtual int Fet@our:;L
R
"irtual int FetMinutes:;L
"irtual int Fet0econd:;L
'loc)Timer:;L
"oid Tic) :;L
L4
8/12/2019 Dp Unit-Vii Jntuworld
48/86
UNIT-VII 4
D#ser"er Pattern , 'oncrete 0u#$ect
2
'loc)Timer Tic) O
== Update internal time )eeping state&
== gets called on regular inter"als #( an internal timer&
R
Noti(:;L
L4
8/12/2019 Dp Unit-Vii Jntuworld
49/86
UNIT-VII 4
D#ser"er Pattern , 'oncrete D#ser"er 1
(lass +igitalClo(, #$%li( -idget #$%li( O%ser/er 0
#$%li(,
+igitalClo(Clo(Ti"er
/irt$al +igitalClo(
/irt$al /oid +ra
#ri/ate,
Clo(Ti"er s$%e(t
/irt$al /oid :#dateS$%e(tOverride Observer operation*
Override +idget operation*
L4
8/12/2019 Dp Unit-Vii Jntuworld
50/86
UNIT-VII 5
D#ser"er Pattern , 'oncrete D#ser"er 2
+igitalClo( ,,+igitalClo( Clo(Ti"er s 0
s$%e(t ; s
s$%e(t
8/12/2019 Dp Unit-Vii Jntuworld
51/86
UNIT-VII 51
D#ser"er Pattern , 'oncrete D#ser"er 3
/oid +igitalClo( ,,:#date s$%e(t t&eC&angedS$%e(t 0
I) t&eC&angedS$%e(t ;; s$%e(t 0
+ra
/oid +igitalClo( ,,+ra 0
int &o$r ; s$%e(t'=>et?o$r
int "in$te ; s$%e(t'=>e!in$te @@ et(.
'hec, if this is the cloc,s sub)ect*
@@ Code )or draing t&e digital (lo(.
L4
8/12/2019 Dp Unit-Vii Jntuworld
52/86
UNIT-VII 52
D#ser"er Pattern Main :s)eleton;
'loc)TimerQ timer G ne! 'loc)TimerL
7igital'loc)Q digital'loc) G ne! 7igital'loc) :timer;L
L4
8/12/2019 Dp Unit-Vii Jntuworld
53/86
UNIT-VII 53
D#ser"er Pattern 'onseEuences
Abstract coupling#et!een su#$ect and o#ser"er&0u#$ect has no )no!ledge o concrete o#ser"er classes&:hat design principle is used;
Support for broadcast communication& , su#$ect need not
speci( the recei"ersL all interested o#$ects recei"e the
notiication&
Unexpected updates D#ser"ers need not #e concerneda#out !hen then updates are to occur& The( are not
concerned a#out each other>s presence& In some cases
this ma( lead to un!anted updates&
L4
8/12/2019 Dp Unit-Vii Jntuworld
54/86
UNIT-VII 54
hen to use the D#ser"er Pattern
Whenan a#straction has t!o aspects one dependenton the other& ?ncapsulating these aspects in separateo#$ects allo!s one to "ar(and reusethemindependentl(&
Whena change to one o#$ect reEuires changing others
and the num#er o o#$ects to #e changed is not )no!n&
Whenan o#$ect should #e a#le to noti( others !ithout)no!ing!ho the( are& ,"oid tight coupling #et!een
o#$ects&
L5
8/12/2019 Dp Unit-Vii Jntuworld
55/86
UNIT-VII 55
0T,T? Pattern
(
8/12/2019 Dp Unit-Vii Jntuworld
56/86
UNIT-VII 5.
Feneral 7escription
, t(pe o eha"ioral pattern&
,llo!s an o#$ect to alter its #eha"ior !henits internal state changes& The o#$ect !ill
appear to change its class&
Uses Pol(morphism to deine dierent
#eha"iors or dierent states o an o#$ect&
hen to use 0T,T? L5
8/12/2019 Dp Unit-Vii Jntuworld
57/86
UNIT-VII 5/
hen to use 0T,T?
pattern
0tate pattern is useul!hen there is an o#$ectthat can #e in one ose"eral states8 !ithdierent #eha"ior in each
state&
To simpli( operationsthat ha"e largeconditional statementsthat depend on theo#$ect>s state&
if (myself = happy) then
eat!ce"ream()#
$%
&
else if (myself = sad) then
go'oub()#
$%
&
else if (myself = ecstatic) then
$%
L5
8/12/2019 Dp Unit-Vii Jntuworld
58/86
UNIT-VII 5
?%ample I
!ater 0tateDater
aterVapor CiEuidater Ice
increaseTemp:;
decreaseTemp:;
state "aria#le
'lientincreaseTemp:;
increaseTemp:;
decreaseTemp:;
increaseTemp:;
decreaseTemp:;
increaseTemp:;
decreaseTemp:;
increaseTemp:;
decreaseTemp:;
@o! is 0T,T? patternL5
8/12/2019 Dp Unit-Vii Jntuworld
59/86
UNIT-VII 5
@o! is 0T,T? pattern
implemented
J'onte%tK class
8/12/2019 Dp Unit-Vii Jntuworld
60/86
UNIT-VII .
?%ample II
M(Mood Mood0tate
do0omething:;
mad angr( happ(
do0omething:; do0omething:; do0omething:;
state "aria#le
'lientdo0omething:;
L5
8/12/2019 Dp Unit-Vii Jntuworld
61/86
UNIT-VII .1
eneits o using 0T,T? pattern
Lo(aliAes all %e&a/ior asso(iated it& a #arti($lar state into one
o%e(t.
Ne! state and transitions can #e added easil( #( deining ne!
su#classes&
0impliies maintenance&
It "aes state transitions eB#li(it.
0eparate o#$ects or separate states ma)es transition e%plicit rather
than using internal data "alues to deine transitions in one com#ined
o#$ect&
State o%e(ts (an %e s&ared.
'onte%t can share 0tate o#$ects i there are no instance "aria#les&
L5
8/12/2019 Dp Unit-Vii Jntuworld
62/86
UNIT-VII .2
*ood or thoughtW
To &a/e a "onolit&i( single (lass or "an* s$%(lasses
Increases the num#er o classes and is less compact&
,"oids large conditional statements&
-&ere to de)ine t&e state transitions I criteria is i%ed8 transition can #e deined in the conte%t&
More le%i#le i transition is speciied in the 0tate su#class&
Introduces dependencies #et!een su#classes&
-&et&er to (reate State o%e(ts as and &en reD$ired or to(reate't&e"'on(e'and'$se'"an*'ti"es *irst is desira#le i the conte%t changes state inreEuentl(&
Cater is desira#le i the conte%t changes state reEuentl(&
L6
8/12/2019 Dp Unit-Vii Jntuworld
63/86
UNIT-VII .3
Pattern 0trateg(
objects that hold alternate algorithms tosolve a problem
0t t ttL6
8/12/2019 Dp Unit-Vii Jntuworld
64/86
UNIT-VII .4
pulling an algorithm out rom the o#$ect that contains it8 and
encapsulating the algorithm :the Xstrateg(X; as an o#$ect
each strateg( implements one #eha"ior8 one implementation o
ho! to sol"e the same pro#lem
6 ho! is this dierent rom Co""andpattern
separates algorithm or #eha"ior rom o#$ect that !ants to act
allo!s changing an o#$ectYs #eha"ior d(namicall( !ithout
e%tending = changing the o#$ect itsel
eBa"#les
6 ile sa"ing=compression
6 la(out managers on FUI containers
6 ,I algorithms or computer game pla(ers
0trateg( pattern
0trateg e ample 'ard pla erL6
8/12/2019 Dp Unit-Vii Jntuworld
65/86
UNIT-VII .5
0trateg( e%ample 'ard pla(er
// Strategy hierarchy parent
// (an interface or abstract class)
public interface Strategy {
public Card getMove();
}
// setting a strategy
player1.setStrategy(ne S!artStrategy());
// using a strategy
Card p1!ove " player1.!ove(); // uses strategy
0trateg( L6
8/12/2019 Dp Unit-Vii Jntuworld
66/86
UNIT-VII ..
0trateg(
?ncapsulating ,lgorithms
%ame&2trategy design pattern
Problem description&
Decouple a policy1deciding class from a set of mechanisms! sothat different mechanisms can be changed transparently.
./ample&
A mobile computer can be used with a wireless networ-! or
connected to an thernet! with dynamic switching betweennetwor-s based on location and networ- costs.
0trateg( L6
8/12/2019 Dp Unit-Vii Jntuworld
67/86
UNIT-VII ./
0 g(
?ncapsulating ,lgorithms
Solution&
A Clientaccesses services provided by a Conte+t.
3he Conte+tservices are reali"ed using one of severalmechanisms! as decided by a (olicyobject.
3he abstract class 2trategydescribes the interface that is common
to all mechanisms that Conte+tcan use. (olicyclass creates a
Concrete2trategyobject and configures Conte+tto use it.
0trateg( ?%ample
L6
8/12/2019 Dp Unit-Vii Jntuworld
68/86
UNIT-VII .
0trateg( ?%ample
'lass 7iagram or Mo#ile 'omputer
?etwor-Connection
send)*set?etwor-#nterface)*
NetworkInterface
open)*
close)*send)*
Application Eocation,anager
thernet
open)*
close)*
send)*
ireless?et
open)*
close)*
send)*
?ote thesimilarities to
'ridge pattern
0trateg( L6
8/12/2019 Dp Unit-Vii Jntuworld
69/86
UNIT-VII .
g(
'lass 7iagram
Conte+t
conte+t#nterface)*Strategy
algorithm#nterface)*
Client
Concrete2trategy%
(olicy
Concrete2trategy5
0trateg( L6
8/12/2019 Dp Unit-Vii Jntuworld
70/86
UNIT-VII /
g(
'onseEuences
'onse(uences&
Concrete2trategiescan be substituted transparently
from Conte+t.
(olicydecides which 2trategyis best! given the current
circumstances.
?ew policy algorithms can be added without modifying
Conte+tor Client.
L6
8/12/2019 Dp Unit-Vii Jntuworld
71/86
UNIT-VII /1
0trateg(
Zou !ant to6 use dierent algorithms depending upon the conte%t
6 a"oid ha"ing to change the conte%t or client
Strategy6 decouples interace rom implementation
6 shields client rom implementations
6 'onte%t is not a!are !hich strateg( is #eing usedL
'lient conigures the 'onte%t6 strategies can #e su#stituted at runtime
6 e%ample interace to !ired and !ireless net!or)s
L6
8/12/2019 Dp Unit-Vii Jntuworld
72/86
UNIT-VII /2
0trateg(
StrategyOperation()
'oncrete0trateg(2Dperation:;
'onte%t
Ma)e algorithms interchangea#le---Kchanging the gutsK ,lternati"e to su#classing 'hoice o implementation at run-time Increases run-time comple%it(
"ontext!nterface()
'oncrete0trateg(1Dperation:;
L7
8/12/2019 Dp Unit-Vii Jntuworld
73/86
UNIT-VII /3
7esign Patterns [*rame!or)s
'hapter . 6 Template Method
'onducted (
8/12/2019 Dp Unit-Vii Jntuworld
74/86
UNIT-VII /4
Topics 6 Template Method Introduction to Template Method
7esign Pattern
0tructure o Template Method
Feneric 'lass and 'oncrete 'lass
Plotter class and Plotter *unction'lass
I t d ti
L7
8/12/2019 Dp Unit-Vii Jntuworld
75/86
UNIT-VII /5
Introduction
3he D'AnimationApplet illustrates the use of an abstract classthat serves as a template for classes with shared functionality.
An abstract class contains behavior that is common to all its
subclasses. 3his behavior is encapsulated in nonabstract methods!
which may even be declared finalto prevent any modification.
3his action ensures that all subclasses will inherit the same
common behavior and its implementation.
3he abstract methods in such templates ensure the interface of thesubclasses and require that conte+t specific behavior be
implemented for each concrete subclass.
L7
8/12/2019 Dp Unit-Vii Jntuworld
76/86
UNIT-VII /.
Foo- ,ethod and 3emplate ,ethod
3he abstract method paintrame)* acts as a placeholder for the
behavior that is implemented differently for each specific conte+t.
e call such methods! hookmethods! upon which conte+tspecific behavior may be hung! or implemented.
3he paintrame)* hoo- is placed within the method update)*!
which is common to all concrete animation applets. ,ethodscontaining hoo-s are called templatemethods.
L7
8/12/2019 Dp Unit-Vii Jntuworld
77/86
UNIT-VII //
3he abstract method paintrame)* represents the behavior
that is changeable! and its implementation is deferred to the
concrete animation applets.
e call paintrame)* a hoo- method. @sing the hoo-
method! we are able to define the update)* method! which
represents a behavior common to all the concrete animation
applets.
Foo- ,ethod and 3emplate ,ethod
)Con/t*
L7
8/12/2019 Dp Unit-Vii Jntuworld
78/86
UNIT-VII /
A template method uses hoo- methods to define a common
behavior.
3emplate method describes the fi+ed behaviors of a genericclass! which are sometimes called fro0en spots.
Foo- methods indicate the changeable behaviors of a
generic class! which are sometimes called hot spots.
ro"en 2pots and Fot 2pots
L7
8/12/2019 Dp Unit-Vii Jntuworld
79/86
UNIT-VII /
3he abstract method paintrame)* represents the behavior
that is changeable! and its implementation is deferred to the
concrete animation applets.
e call paintrame)* a hoo- method. @sing the hoo-
method! we are able to define the update)* method! which
represents a behavior common to all the concrete animation
applets.
Foo- ,ethod and 3emplate ,ethod
)Con/t*
St t ) t& T l t ! t& d + i
L7
8/12/2019 Dp Unit-Vii Jntuworld
80/86
UNIT-VII
Str$(t$re o) t&e Te"#late !et&od +esign
Pattern
Feneric'lasstemplateMethod:;
hoo*ethod+()
hoo*ethod,()
'oncrete'lass
hoo)Method1:;
hoo)Method2:;
G
hoo-,ethod5)*
G
hoo-,ethod%)*
G
L7
8/12/2019 Dp Unit-Vii Jntuworld
81/86
UNIT-VII 1
1eneric'lass)e.g.! D'AnimationApplet*! which defines
abstract hoo- methods )e.g.! paintrame)** that concrete
subclasses )e.g.! 'ouncing1'all%* override to implement
steps of an algorithm and implements a template method
)e.g.! update)** that defines the s-eleton of an algorithm by
calling the hoo- methods
'oncrete'lass)e.g.! 'ouncing1'all%* which
implements the hoo- methods )e.g.! paintrame)** to
carry out subclass specific steps of the algorithm
defined in the template method.
Structure of the Template Method 2esign Pattern 'ont"
L7
8/12/2019 Dp Unit-Vii Jntuworld
82/86
UNIT-VII 2
#n the 3emplate ,ethod design pattern! hook methodsdo
nothave to be abstract.
3he generic class may provide default implementations for
the hoo- methods.
3hus the subclasses have the option of overriding the hoo-
methods or using the default implementation.
3he initAnimator)* method in D'AnimationApplet is a
nonabstract hoo- method with a default implementation.
3he init)* method is another template method.
Structure of the Template Method 2esign Pattern 'ont"
L8
8/12/2019 Dp Unit-Vii Jntuworld
83/86
UNIT-VII 3
3he generic plotter should factori"e all the behavior related to
drawing and leave only the definition of the function to be plotted
to its subclasses.
A concrete plotter (lot2ine will be implemented to plot the function
y = sin x
3 1eneric 4unction Plotter
L8
8/12/2019 Dp Unit-Vii Jntuworld
84/86
UNIT-VII 4
Pattern @atching
Visitor pattern
Visitor
Visited
instance
"isited&accept:this;L
"&"isit:this;L
L8
8/12/2019 Dp Unit-Vii Jntuworld
85/86
UNIT-VII 5
Pattern @atching
Visitor Pattern
Class Eisitor 0
#$%li(,
Eisitor
/oid /isitFile
/oid /isit+ire(tor*
/oid /isit Lin
/oid Eisitor,,/isit File )
0)'=strea"O$t(o$t
/oid Eisitor,,/isit +ire(tor* d
0(err GG Hno #rinto$t )or adire(tor*
/oid Eisitor,,/isit Lin l
0l'=getS$%e(t'=a((e#tt&is
Eisitor (at
node'=a((e#t(at
/oid File,,a((e#t EisitorJ /0/./isitt&is
/oid +ire(tor*,,a((e#t EisitorJ /0/./isitt&is
/oid Lin,,a((e#t EisitorJ /0/./isitt&is
8/12/2019 Dp Unit-Vii Jntuworld
86/86