Vous êtes sur la page 1sur 86

S.

No 1 2 3 4 5 6 7 8 9

TOPIC

PPT Slides
L1 L2 L3 L4 L5 L6 L7 L8 L9 UNIT-VII 1 24 5 12 13 32 33 54 55 62 63 73 74 82 83 85 86 86

Behavioral patterns part-II introduction Mediator Memento Observer State Strategy Template Method Visitor Reference

L1

Behavioral Patterns !"


Deal with the way objects interact and distribute responsibility 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 the language.
%& UNIT-VII 2

'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

UNIT-VII

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 algorithm in 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.
UNIT-VII 4

L1

The Mediator Pattern


The Mediator pattern reduces coupling and simpli ies code !hen se"eral o#$ects must negotiate a comple% interaction& 'lasses interact onl( !ith a mediator class rather 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
UNIT-VII 5

L2

Using a Mediator

L2

UNIT-VII

Mediator Pattern 0tructure

L2

UNIT-VII

Mediator as a 2ro)er

L2

UNIT-VII

Mediator 2eha"ior

L2

UNIT-VII

5hen 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&

L2

Using a mediator ma( compromise per ormance&


UNIT-VII 14

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 delegated st(le8 #ut not rom a delegated to a centrali9ed st(le&
UNIT-VII 11

L2

0ummar(
2ro)er patterns use a 2ro)er class to acilitate the interaction #et!een a 'lient and a 0upplier& The *a+ade pattern uses a #ro)er :the a+ade; to pro"ide a simpli ied inter ace to a comple% su#-s(stem& The Mediator pattern uses a #ro)er to encapsulate and control a comple% interaction among se"eral suppliers&
UNIT-VII 12

L2

L3

Memento Pattern

UNIT-VII

13

L3

<e erences
do*actor(&com Marc 'li ton>s 2log
6 http-==!!!&marccli ton&com=ta#id=33=7e ault&asp%

6 http-==!!!&do actor(&com=Patterns=PatternMemento&asp%

0o t!are ,rchitecture8 ?T@8 Aurich 0!it9erland

6 http-==se&eth9&ch=teaching=ss2445=4454=slides=.4Bso tarch

UNIT-VII

14

Intent
'apture and e%ternali9e an o#$ect>s state !ithout "iolating encapsulation& <estore the o#$ect>s state at some later time&
6 Use ul !hen implementing chec)points and undo mechanisms that let users #ac) out o tentati"e operations or reco"er rom errors& 6 ?ntrusts other o#$ects !ith the in ormation it needs to re"ert to a pre"ious state !ithout e%posing its internal structure and representations&
UNIT-VII 15

L3

L3

*orces
,pplication needs to capture states at certain times or at user discretion& Ma( #e used or6 Undue = redo 6 Cog errors or e"ents 6 2ac)trac)ing

Need to preser"e encapsulation


6 7on>t share )no!ledge o state !ith other o#$ects

D#$ect o!ning state ma( not )no! !hen to ta)e state snapshot&
UNIT-VII 1.

L3

Moti"ation
Man( technical processes in"ol"e the e%ploration o some comple% data structure& D ten !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&
UNIT-VII 1/

L3

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 inter ace might #e insu icient to allo! precise re"ersal o a move operation&
$ndo Move
UNIT-VII 11

L3

Moti"ation
Memento pattern sol"es this pro#lem as ollo!s The editor reEuests a memento rom the o#$ect #e ore e%ecuting move operation& Driginator creates and returns a memento& 7uring undo operation8 the editor gi"es the memento #ac) to the originator& 2ased on the in ormation in the memento8 the originator restores itsel to its pre"ious state&
UNIT-VII 13

L3

,pplica#ilit(
Use the Memento pattern !hen6 , snapshot o an o#$ect>s state must #e sa"ed so that it can #e restored later8 and 6 direct access to the state !ould e%pose implementation details and #rea) encapsulation&

UNIT-VII

24

L3

0tructure
Driginator
,ttri#utestate Dperation0etMemento:Memento m; 'reateMemento: ;

Memento
,ttri#utestate DperationFet0tate: ; 0et0tate: ;

careta)er

state G m-HFet0tate: ;

return ne! Memento:state;

UNIT-VII

21

L3

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 inter aces 'areta)er sees a narro! inter ace& Driginator sees a !ide inter ace&
UNIT-VII 22

L3

Participants :continued;
Driginator
6 'reates a memento containing a snapshot o its current internal state& 6 Uses the memento to restore its internal state&

UNIT-VII

23

L3

'areta)er
Is responsi#le or the memento>s sa e)eeping& Ne"er operates on or e%amines the contents o a memento&

UNIT-VII

24

L3

?"ent Trace
aCareta er anOriginator a!e"ento

'reateMemento: ; ne! Memento

0et0tate: ;

0etMemento:aMemento; Fet0tate: ;

UNIT-VII

25

L3

'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 !ill assign or retrie"e its state&
UNIT-VII 2.

L3

'onseEuences
Memento has se"eral conseEuences6 Memento a"oids e%posing in ormation that onl( an originator should manage8 #ut or simplicit( should #e stored outside the originator& 6 @a"ing clients manage the state the( as) or simpli ies the originator&

UNIT-VII

2/

L3

'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&
UNIT-VII 21

L3

Implementation
5hen mementos get created and passed #ac) to their originator in a predicta#le seEuence8 then Memento can sa"e $ust incremental changes to originator>s state&

UNIT-VII

23

L3

Ino!n Uses
Memento is a 2444 ilm a#out Ceonard 0hel#( and his Euest to re"enge the #rutal murder o his !i e& Though Ceonard is hampered !ith short-term memor( loss8 he uses notes and tatoos to compile the in ormation into a suspect&

UNIT-VII

34

L3

Ino!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 oriented language using the unctional st(le& 6 7e"elopment started #( ,pple8 #ut su#seEuentl( mo"ed to open source&

UNIT-VII

31

L3

<elated Patterns
'ommand 'ommands can use mementos to maintain state or undo mechanisms& Iterator
Mementos can #e used or iteration&

UNIT-VII

32

L4

D#ser"er Pattern
7e ine a one-to-man( dependenc(8 all the dependents are noti ied and updated automaticall( The interaction is )no!n as #$%lis&' s$%s(ri%e or s$%s(ri%e'noti)* ,"oiding o#ser"er-speci ic update protocol- #$ll "odel "s& #$s& "odel Dther conseEuences and open issues
UNIT-VII 33

L4

D#ser"er Pattern
Intent6 7e ine a one-to-man( dependenc( #et!een o#$ects so that !hen one o#$ect changes state8 all its dependents are noti ied and updated automaticall(

Ie( orces6 There ma( #e man( o#ser"ers 6 ?ach o#ser"er ma( react di erentl( to the same noti ication 6 The su#$ect should #e as decoupled as possi#le rom the o#ser"ers to allo! o#ser"ers to change independentl( o the su#$ect
UNIT-VII 34

L4

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 noti ication st(les

Subject
attach:D#ser"er; detach:D#ser"er; noti (:;

Observer
orall o in o#ser"ers o&update:;
update()

'oncrete0u#$ect
get0tate:;

'oncreteD#ser"er
update:;

UNIT-VII

stateGsu#$ect&get0tate:;L 35

D#ser"er?ncapsulating 'ontrol *lo!


%ame& 0bserver design pattern Problem description& ,aintains consistency across state of one 2ubject and many 0bservers. Solution& A 2ubject has a primary function to maintain some state )e.g.! a data structure*. 0ne or more 0bservers use this state! which introduces redundancy between the states of 2ubject and 0bserver. 0bserver invo-es the subscribe)* method to synchroni"e the state. .henever the state changes! 2ubject invo-es its notify)* method to iteratively invo-e each 0bserver.update)* method. 3. UNIT-VII

L4

D#ser"er'lass 7iagram
2ubject subscribe)* unsubscribe)* notify)* 5 subscribers 6 Observer update)*

L4

Concrete2ubject state getstate)* setstate)*


UNIT-VII

Concrete0bserver observe2tate update)*


3/

L4

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 2ubject changes.

UNIT-VII

31

L4

'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:;

UNIT-VII

33

L4

D#ser"er Pattern M1N


Need to separate presentational aspects !ith the data8 i&e& separate "ie!s and data&

'lasses de ining application data and presentation can #e reused&

'hange in one "ie! automaticall( re lected in other "ie!s& ,lso8 change in the application data is re lected in all "ie!s&
7e ines one-to-man( dependenc( amongst o#$ects so that !hen one o#$ect changes its state8 all its dependents are noti ied&

UNIT-VII

44

L4

D#ser"er Pattern M2N


Relative (ercentages

A ' C D < ; > 5= &= &= 5= 58 :8 &8 %8 58 :8 &8 %8 A ' C D D

A ' C

Change notification Requests! modifications

A7589 '7:89 C7&89 D7%89


UNIT-VII

Application data
41

D#ser"er Pattern M3N


observers Subject
attach )0bserver* detach )0bserver* ?otify )*

L4

Observer
@pdate)*

Aor all + in observersB + @pdate)*C D 'oncrete Observer subject

'oncrete Sub)ect
$et2tate)* 2et2tate)* subject2tate UNIT-VII

@pdate)* observer2tate

observer2tate7 subject get2tate)*C


42

L4

'lass colla#oration in D#ser"er


:Concrete2ubject
:Concrete0bserver15 :Concrete0bserver1%

2et2tate)* ?otify)* @pdate)* $et2tate)* @pdate)* $et2tate)*


UNIT-VII 43

L4

D#ser"er Pattern- D#ser"er code


class 0u#$ectL class o#ser"er O pu#lic"irtual Po#ser"erL "irtual "oid Update :0u#$ectQ the'hanged0u#$ect;G4L

Abstract class defining the 0bserver interface.

protectedo#ser"er :;L

RL

?ote the support for multiple subjects.


UNIT-VII 44

L4

D#ser"er Pattern- 0u#$ect 'ode M1N


class 0u#$ect O

pu#lic"irtual P0u#$ectL

Abstract class defining the 2ubject interface.

"irtual "oid ,ttach :o#ser"erQ;L "irtual "oid 7etach :o#ser"erQ; L "irtual "oid Noti (:;L

protected0u#$ect :;L

pri"ateCist SD#ser"erQH QBo#ser"ersL

RL UNIT-VII 45

L4

D#ser"er Pattern- 0u#$ect 'ode M2N


"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 <emo"e:o;L

R "oid 0u#$ect -- Noti ( :;O


CistIteratorSD#ser"erQH iter:Bo#ser"ers;L or : iter&*irst:;L Titer&Is7one:;L iter&Ne%t:;; O
iter&'urrentItem:; -H Update:this;L
R

UNIT-VII

4.

L4

D#ser"er Pattern- , 'oncrete 0u#$ect M1N


class 'loc)Timer - pu#lic 0u#$ect O pu#lic'loc)Timer:;L "irtual int Fet@our:;L "irtual int FetMinutes:;L "irtual int Fet0econd:;L "oid Tic) :;L
R

UNIT-VII

4/

L4

D#ser"er Pattern- , 'oncrete 0u#$ect M2N


'loc)Timer -- Tic) O == Update internal time )eeping state& == gets called on regular inter"als #( an internal timer&

Noti (:;L
R

UNIT-VII

41

L4

D#ser"er Pattern- , 'oncrete D#ser"er M1N


(lass +igitalClo( , #$%li( -idget. #$%li( O%ser/er 0

#$%li(,
+igitalClo( 1Clo( Ti"er234 /irt$al 5+igitalClo( 134 /irt$al /oid :#date1S$%9e(t234 /irt$al /oid +ra6134

Override Observer operation* Override +idget operation*

#ri/ate,
Clo( Ti"er2 8s$%9e(t4
7

UNIT-VII

43

L4

D#ser"er Pattern- , 'oncrete D#ser"er M2N


+igitalClo( ,,+igitalClo( 1Clo( Ti"er2 s3 0
8s$%9e(t ; s4 8s$%9e(t <tta(&1t&is34
7

+igitalClo( ,,5+igitalClo( 13 0
8s$%9e(t'=+eta(&1t&is34
7

UNIT-VII

54

L4

D#ser"er Pattern- , 'oncrete D#ser"er M3N


/oid +igitalClo( ,,:#date 1s$%9e(t2 t&eC&angedS$%9e(t 3 0 I) 1t&eC&angedS$%9e(t ;; 8s$%9e(t3 0 +ra6134
7

'hec, if this is the cloc,-s sub)ect*

/oid +igitalClo( ,,+ra6 13 0 int &o$r ; 8s$%9e(t'=>et?o$r134 int "in$te ; 8s$%9e(t'=>e!in$te134 @@ et(. @@ Code )or dra6ing t&e digital (lo( .
7

UNIT-VII

51

L4

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

UNIT-VII

52

L4

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& :5hat design principle is usedU;
Support for broadcast communication& , su#$ect need not speci ( the recei"ersL all interested o#$ects recei"e the noti ication&

Unexpected updates- D#ser"ers need not #e concerned a#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&
UNIT-VII 53

L4

5hen to use the D#ser"er PatternU


When an a#straction has t!o aspects- one dependent on the other& ?ncapsulating these aspects in separate o#$ects allo!s one to "ar( and reuse them independentl(& When a change to one o#$ect reEuires changing others and the num#er o o#$ects to #e changed is not )no!n& When an o#$ect should #e a#le to noti ( others !ithout )no!ing !ho the( are& ,"oid tight coupling #et!een o#$ects&
UNIT-VII 54

L5

0T,T? Pattern
2( <agha"endar Vapala

UNIT-VII

55

L5

Feneral 7escription
, t(pe o 2eha"ioral pattern& ,llo!s an o#$ect to alter its #eha"ior !hen its internal state changes& The o#$ect !ill appear to change its class& Uses Pol(morphism to de ine di erent #eha"iors or di erent states o an o#$ect&
UNIT-VII 5.

5hen to use 0T,T? pattern U


0tate pattern is use ul !hen there is an o#$ect that can #e in one o se"eral states8 !ith di erent #eha"ior in each state& To simpli ( operations that ha"e large conditional statements that depend on the o#$ect>s state&
if (myself = happy) then eat!ce"ream()# $% & else if (myself = sad) then go'o(ub()# $% & else if (myself = ecstatic) then $%
5/

L5

UNIT-VII

L5

?%ample I
!ater state "aria#le
increaseTemp:; decreaseTemp:;

0tateD 5ater
increaseTemp:; decreaseTemp:;

5aterVapor 'lient
increaseTemp:; increaseTemp:; decreaseTemp:;

CiEuid5ater
increaseTemp:; decreaseTemp:;

Ice
increaseTemp:; decreaseTemp:;

UNIT-VII

51

@o! is 0T,T? pattern implemented U


J'onte%tK class<epresents the inter ace to the outside !orld& J0tateK a#stract class2ase class !hich de ines the di erent states o the Jstate machineK& J7eri"edK classes rom the 0tate class7e ines the true nature o the state that the state machine can #e in& 'onte%t class maintains a pointer to the current state& To change the state o the state machine8 the pointer needs to #e changed&
UNIT-VII 53

L5

L5

?%ample II
M(Mood state "aria#le
do0omething:;

Mood0tate

mad 'lient
do0omething:;

angr(

happ(

do0omething:;

do0omething:;

do0omething:;

UNIT-VII

.4

L5

2ene its o using 0T,T? pattern


Lo(aliAes all %e&a/ior asso(iated 6it& a #arti($lar state into one o%9e(t.
Ne! state and transitions can #e added easil( #( de ining ne! su#classes& 0impli ies maintenance&

It "a es state transitions eB#li(it.


0eparate o#$ects or separate states ma)es transition e%plicit rather than using internal data "alues to de ine transitions in one com#ined o#$ect&

State o%9e(ts (an %e s&ared.


'onte%t can share 0tate o#$ects i there are no instance "aria#les& UNIT-VII .1

L5

*ood or thoughtW
To &a/e a "onolit&i( single (lass or "an* s$%(lasses C Increases the num#er o classes and is less compact& ,"oids large conditional statements& -&ere to de)ine t&e state transitions C I criteria is i%ed8 transition can #e de ined in the conte%t& More le%i#le i transition is speci ied in the 0tate su#class& Introduces dependencies #et!een su#classes& -&et&er to (reate State o%9e(ts as and 6&en reD$ired or to (reate't&e"'on(e'and'$se'"an*'ti"es C
*irst is desira#le i the conte%t changes state in reEuentl(& Cater is desira#le i the conte%t changes state reEuentl(&

UNIT-VII

.2

L6

Pattern- 0trateg(
objects that hold alternate algorithms to solve a problem

UNIT-VII

.3

L6

0trateg( pattern
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 di erent rom Co""and patternU

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"#les6 ile sa"ing=compression 6 la(out managers on FUI containers 6 ,I algorithms or computer game pla(ers UNIT-VII

.4

L6

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();


UNIT-VII

// uses strategy
.5

0trateg(?ncapsulating ,lgorithms
%ame& 2trategy design pattern Problem description& Decouple a policy1deciding class from a set of mechanisms! so that 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 between networ-s based on location and networ- costs.
UNIT-VII ..

L6

0trateg(?ncapsulating ,lgorithms
Solution& A Client accesses services provided by a Conte+t. 3he Conte+t services are reali"ed using one of several mechanisms! as decided by a (olicy object. 3he abstract class 2trategy describes the interface that is common to all mechanisms that Conte+t can use. (olicy class creates a Concrete2trategy object and configures Conte+t to use it.

L6

UNIT-VII

./

0trateg( ?%ample'lass 7iagram or Mo#ile 'omputer


Application Eocation,anager NetworkInterface ?etwor-Connection send)* set?etwor-#nterface)* ?ote the similarities to 'ridge pattern open)* close)* send)*

L6

thernet open)* close)* send)*

.ireless?et open)* close)* send)*


.1

UNIT-VII

0trateg('lass 7iagram
Client Conte+t conte+t#nterface)* (olicy

L6

Strategy algorithm#nterface)*

Concrete2trategy5

Concrete2trategy%

UNIT-VII

.3

0trateg('onseEuences
'onse(uences& Concrete2trategies can be substituted transparently from Conte+t. (olicy decides which 2trategy is best! given the current circumstances. ?ew policy algorithms can be added without modifying Conte+t or Client.

L6

UNIT-VII

/4

L6

0trateg(
Zou !ant to
6 use di erent algorithms depending upon the conte%t 6 a"oid ha"ing to change the conte%t or client

Strategy
6 decouples inter ace rom implementation 6 shields client rom implementations 6 'onte%t is not a!are !hich strateg( is #eing usedL 'lient con igures the 'onte%t 6 strategies can #e su#stituted at runtime 6 e%ample- inter ace to !ired and !ireless net!or)s
UNIT-VII /1

L6

0trateg(
Ma)e algorithms interchangea#le---Kchanging the gutsK ,lternati"e to su#classing 'hoice o implementation at run-time Increases run-time comple%it(

'onte%t
"ontext!nterface()

Strategy
Operation()

'oncrete0trateg(1 'oncrete0trateg(2
Dperation:; Dperation:;

UNIT-VII

/2

L7

7esign Patterns [ *rame!or)s


'hapter . 6 Template

Method

'onducted 2( <agha"endar Vapala


UNIT-VII /3

L7

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
UNIT-VII /4

L7

Introduction
3he D'AnimationApplet illustrates the use of an abstract class that 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 final to 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 the subclasses and require that conte+t specific behavior be implemented for each concrete subclass.
UNIT-VII /5

L7

Foo- ,ethod and 3emplate ,ethod


3he abstract method paintArame)* acts as a placeholder for the behavior that is implemented differently for each specific conte+t. .e call such methods! hook methods! upon which conte+t specific behavior may be hung! or implemented. 3he paintArame)* hoo- is placed within the method update)*! which is common to all concrete animation applets. ,ethods containing hoo-s are called template methods.

UNIT-VII

/.

L7

Foo- ,ethod and 3emplate ,ethod )Con/t*


3he abstract method paintArame)* represents the behavior that is changeable! and its implementation is deferred to the concrete animation applets. .e call paintArame)* a hoo- method. @sing the hoomethod! we are able to define the update)* method! which represents a behavior common to all the concrete animation applets.

UNIT-VII

//

L7

Aro"en 2pots and Fot 2pots


A template method uses hoo- methods to define a common behavior. 3emplate method describes the fi+ed behaviors of a generic class! which are sometimes called fro0en spots. Foo- methods indicate the changeable behaviors of a generic class! which are sometimes called hot spots.

UNIT-VII

/1

L7

Foo- ,ethod and 3emplate ,ethod )Con/t*


3he abstract method paintArame)* represents the behavior that is changeable! and its implementation is deferred to the concrete animation applets. .e call paintArame)* a hoo- method. @sing the hoomethod! we are able to define the update)* method! which represents a behavior common to all the concrete animation applets.

UNIT-VII

/3

L7

Str$(t$re o) t&e Te"#late !et&od +esign Pattern


Feneric'lass templateMethod:; hoo)*ethod+() hoo)*ethod,() G hoo-,ethod5)* G hoo-,ethod%)* G

'oncrete'lass hoo)Method1:; hoo)Method2:;


UNIT-VII 14

L7

Structure of the Template Method 2esign Pattern 'on-t" 1eneric'lass )e.g.! D'AnimationApplet*! which defines abstract hoo- methods )e.g.! paintArame)** 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- methodsC 'oncrete'lass )e.g.! 'ouncing1'all%* which implements the hoo- methods )e.g.! paintArame)** to carry out subclass specific steps of the algorithm defined in the template method.
UNIT-VII 11

L7

Structure of the Template Method 2esign Pattern 'on-t" #n the 3emplate ,ethod design pattern! hook methods do not have to be abstract. 3he generic class may provide default implementations for the hoo- methods. 3hus the subclasses have the option of overriding the hoomethods or using the default implementation. 3he initAnimator)* method in D'AnimationApplet is a nonabstract hoo- method with a default implementation. 3he init)* method is UNIT-VII another template method.
12

L8

3 1eneric 4unction Plotter


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

UNIT-VII

13

L8

Pattern @atching
Visitor pattern

"isited&accept:this;L

Visitor

"&"isit:this;L

Visited instance

UNIT-VII

14

L8

Pattern @atching
Visitor Pattern
Class Eisitor 0 #$%li(, Eisitor134 /oid /isit1File234 /oid /isit1+ire(tor*234 /oid /isit 1Lin 234 74 /oid Eisitor,,/isit 1+ire(tor*2 d3 0(err GG Hno #rinto$t )or a dire(tor*I47 /oid Eisitor,,/isit 1Lin 2 l3 0l'=getS$%9e(t13'=a((e#t12t&is347 /oid File,,a((e#t 1EisitorJ /3 0/./isit1t&is347 /oid +ire(tor*,,a((e#t 1EisitorJ /3 0/./isit1t&is347 /oid Eisitor,,/isit 1File2 )3 0)'=strea"O$t1(o$t347

Eisitor (at4 node'=a((e#t1(at34

UNIT-VII 15 /oid Lin ,,a((e#t 1EisitorJ /3


0/./isit1t&is347

L9

<e erences
Va"a ,PI pages
6 6 6 6 6 http-==$a"a&sun&com=$2se=1&4&2=docs=api=$a"a=util='ollection&html http-==$a"a&sun&com=$2se=1&4&2=docs=api=$a"a=util=Iterator&html http-==$a"a&sun&com=$2se=1&4&2=docs=api=$a"a=a!t='ontainer&html http-==$a"a&sun&com=$2se=1&4&2=docs=api=$a"a=a!t=Ca(outManager&html http-==$a"a&sun&com=$2se=1&4&2=docs=api=$a"a%=s!ing=V0crollPane&html

'unningham [ 'unningham DD 'onsultanc(8 Inc&


6 http-==c2&com=cgi=!i)iUIteratorPattern 6 http-==c2&com=cgi=!i)iU7ecoratorPattern 6 http-==c2&com=cgi=!i)iU'ompositePattern

7esign Patterns Va"a 'ompanion


6 http-==!!!&patterndepot&com=put=1=Va"aPatterns&htm UNIT-VII 1.

Vous aimerez peut-être aussi