Download - designPatterns-05.pdf
-
7/29/2019 designPatterns-05.pdf
1/33
The Observer Pattern
CSCI 3132 Summer 20111
-
7/29/2019 designPatterns-05.pdf
2/33
SevenSinsofDesign
Rigiditymakeithardtochange FragilitymakeiteasytobreakImmobilitymakeithardtoreuse
Viscositymakeithardtodotherightthing NeedlessComplexityoverdesignNeedlessRepeAAonerrorprone
Notdoingany2
-
7/29/2019 designPatterns-05.pdf
3/33
TheRules
pplyCommonSense DontgettoodogmaAc/religious Everydecisionisatradeoff llotherprinciplesarejustthat
GuidelinesbestpracAcesConsidercarefullyifyoushouldviolatethem-but,
knowyoucan.
3
-
7/29/2019 designPatterns-05.pdf
4/33
OpenClosedPrinciple
SowareenAAes(Classes,Modules,Methods,etc.)shouldbeopenforextension,butclosed
formodificaAon.
lsoKnownsProtectedVariaAon QuesAon:ThisprincipleisappliedtowhichofthedesignpaZernswehavelearnedsofar?
4
-
7/29/2019 designPatterns-05.pdf
5/33
SingleResponsibilityPrinciple
ClassshouldhaveonereasontochangeResponsibilityisareasonstochange
Canbetrickytogetgranularityright SingleResponsibility=increasedcohesion Notfollowingresultsinneedlessdependencies
Morereasonstochange.Rigidity,Immobility
QuesAon:ThisprincipleisappliedtowhichofthedesignpaZernswehavelearnedsofar?
5
-
7/29/2019 designPatterns-05.pdf
6/33
ConsidertheFollowingpplicaAon
Humidity
Temperature
Pressure
Weather
StaAon
Weather
Data
Object
Three
Displays
6
-
7/29/2019 designPatterns-05.pdf
7/33
WhatsGiven
TheWeatherDataclasshasgeZermethodsthatobtainmeasurementvaluesfromtemperature,humidityandpressure.
TheclasshasameasurementsChanged()methodthatupdatesthethreevalues. Threedisplaysmustbeimplemented:current
condiAons,staAsAcsandforecastdisplay.
Systemmustbeexpandableotherdisplayelementsmaybeaddedorremoved.7
-
7/29/2019 designPatterns-05.pdf
8/33
FirstZempt
class WeatherData{!public: ! !void measurementChanged(){!
! ! float temp = getTemperature();!! ! float humidity = getHumidity();!! ! float pressure = getPressure();!! ! currentConditionsDisplay.update(temp,humidity,!! ! ! ! ! pressure)!! !! statisticsDisplay.update(temp,humidity,pressure)!! !! forecastDisplay.update(temp,humidity,pressure)!}!! //other WeatherData methods here!
}; !
8
-
7/29/2019 designPatterns-05.pdf
9/33
TheObserverPaZernObserved
SubjectObject
int2
Dog Object Registers
Observers
Dog
Object
Cat
Object
Duck
Object
SubjectBroadcasts
2
CatObjectRegistersDuckObjectRegistersSubjectisupdated
int8
Catobjectde-registers
Cat
Object
SubjectBroadcasts
8
8
Other examples: publish and
subscription services; eBay
9
-
7/29/2019 designPatterns-05.pdf
10/33
HandlingtheaddiAonofnewcustomers:
SendingawelcomeleZer Verifythecustomersaddresswiththepostoffice
notherExample
10
-
7/29/2019 designPatterns-05.pdf
11/33
Customer:Whenacustomerisadded,thisobjectwillmakethe
callstotheotherobjectstohavethecorresponding
acAonstakeplace
WelcomeLeZer: CreateswelcomeleZersforcustomersthatlet
themknowtheywereaddedtothesystem.
ddrVerificaAon: Thisobjectwillverifytheaddressofany
customerthatasksitto
FirstTry
11
-
7/29/2019 designPatterns-05.pdf
12/33
WedonotwanttochangethebroadcasAngobjectevery
Amethereisachangetothesetofobjectslisteningto
thebroadcast.
WewanttodecouplethenoAfy-ers(subject)andthenoAfy-
ees(observer).
Twothingsvary DifferentkindsofobjectsonesthatneedtobenoAfied
ofachangeinstate.
DifferentinterfacesEachobjectthatrequiresnoAficaAonmayhaveadifferentinterface.
Decoupling
12
-
7/29/2019 designPatterns-05.pdf
13/33
llobserversmusthavethesameinterface.llobserversmustregisterthemselves.Thismakesthem
responsibleforknowingwhattheyarewatchingfor.
Wemustaddtwomethodstothesubject.
attach(Observer) addsthegivenobservertoitslistofobservers.
detatch(Observer) removesthegivenobserverfromitslistofobservers.
Theobservermustimplementamethodcalledupdate.Thesubjectimplementsthenotifymethodthatgoes
throughitslistofObserversandcallsthisupdatemethod
foreachofthem.
BeZerSoluAon
13
-
7/29/2019 designPatterns-05.pdf
14/33
TheClassDiagram
14
-
7/29/2019 designPatterns-05.pdf
15/33
class Customer{!public:!
void attach( Observer *myObserver);!void detach( Observer *myObserver);!void notify();!
private:!vector myObs;!
};!void Customer::attach( Observer *myObserver)!{!
myObs.push_back( myObserver);!}!
Example(Contd)
15
-
7/29/2019 designPatterns-05.pdf
16/33
void Customer::detach( Observer *myObserver){!for (int i= 0; i< myObs.size(); i++){!
if (myObs[i]== myObserver){!myObs.erase(myObs.begin()+i);!return;!}!
}!}!void Customer::notify(){!
for (int i= 0; i< myObs.size(); i++){!myObs[i]->update(this);!}!
}!
Example(Contd)
16
-
7/29/2019 designPatterns-05.pdf
17/33
DefiniAon
TheobserverpaZernimplementsaone-to-manyrelaAonshipbetweenasetofobjects.
singleobjectchangesstateandupdatestheobjects(dependants)thatareaffectedbythechange.
Theobjectthatchangesstateiscalledthe subjectandtheotherobjectsaretheobservers.
17
-
7/29/2019 designPatterns-05.pdf
18/33
LooseCoupling
Subjectsandobserversarelooselycoupled. Thesubjectonlyknowstheobserverinterfaceand
notitsimplementaAon.
ObserverscanbeaddedandremovedatanyAme. Inaddingnewobserversthesubjectdoesnotneed
tobemodified.
Subjectsandobserverscanbereusedindependently.
Changestothesubjectorobserverwillnotaffecttheother.
18
-
7/29/2019 designPatterns-05.pdf
19/33
DesignPrinciple
Striveforlooselycoupleddesignsbetweenobjectsthatinteract.
Looselycoupleddesignsallowustobuildflexibleobject-orientedsystems.
Thesesystemscanhandlechangebecausetheyminimizetheinterdependencybetweenobjects.
19
-
7/29/2019 designPatterns-05.pdf
20/33
Observerpplicability
UsetheObserverpaZerninanyofthefollowingsituaAons
WhenanabstracAonhastwoaspects,onedependentontheother.EncapsulaAngtheseaspectsinseparateobjectsletsyouvaryandreusethemindependtly.
Whenachangetooneobjectrequireschangingothers,andyoudonotknowhow
manyobjectsneedtobechanged.
WhenanobjectshouldbeabletonoAfyotherobjectswithoutmakingassumpAonsaboutwhotheseobjectsare.
20
-
7/29/2019 designPatterns-05.pdf
21/33
ObserverParAcipants
SubjectKnowsitsobservers.nynumberofObserver
objectsmayobserveasubject.
ProvidesaninterfaceforaZachinganddetachingObserverObjects.
ObserverDefinesanupdaAnginterfaceforobjectsthat
shouldbenoAfiedofchangesinasubject
21
-
7/29/2019 designPatterns-05.pdf
22/33
ObserverParAcipants
ConcreteSubjectStoresastateofinteresttoConcreteObserver
objects.
SendsanoAficaAontoitsobserverswhenitsstatechanges.
ConcreteObserverMaintainsareferencetoaConcreteSubjectobjectStoresstatethatshouldstayconsistentwiththe
subjectstate.
ImplementstheObserverupdaAnginterfacetokeepitsstateconsistentwiththesubjectstate. 22
-
7/29/2019 designPatterns-05.pdf
23/33
WeatherStaAonClassDiagram
23
-
7/29/2019 designPatterns-05.pdf
24/33
TheObserverPaZern:KeyFeatures
Intent:Defineaone-to-manydependencybetweenobjectssothatwhenoneobjectchangesstate,allitsdependentsarenoAfiedandupdatedautomaAcally.
Problem:YouneedtonoAfyavaryinglistofobjectsthatan
eventhasoccurred.
Solu.on:Observersdelegatetheresponsibilityformonitoringforaneventtoacentralobject:Thesubject.
24
-
7/29/2019 designPatterns-05.pdf
25/33
TheObserverPaZern:KeyFeatures
Implementa.on:Haveobjects(Observers)thatwanttoknowwhenaneventhappenaZachthemselvestoanotherobject(Subject)thatiswatchingfortheeventtooccurorthattriggerstheeventitself.
Whentheeventoccurs,theSubjecttellstheObserversthatithasoccurred.
ThedapterpaZernissomeAmesneededtobeable
toimplementtheObserverinterfaceforalltheObserver-typeobjects.
25
-
7/29/2019 designPatterns-05.pdf
26/33
ObserverPaZern:ClassDiagram
26
-
7/29/2019 designPatterns-05.pdf
27/33
ObserverSequenceDiagram
ConcreteSubjectObject
ConcreteObserverObjectA
ConcreteObserverObjectB
Notify()
SetState()
Update()
GetState()
Update()
GetState()
27
-
7/29/2019 designPatterns-05.pdf
28/33
ObserverConsequences
bstractcouplingbetweenSubjectandObjectllasubjectknowsisthatithasalistof
observers,eachconformingtothesimple
interfaceoftheabstractObserverclass.Thesubjectdoesnotknowtheconcreteclassofanyobserver.
SupportforbroadcastcommunicaAonUnlikeandordinaryrequest,thenoAficaAonthat
asubjectsendsneednotspecifyitsreceiver.ThenoAficaAonisbroadcastautomaAcallytoallinterestedobjectsthatsubscribedtoit.
28
-
7/29/2019 designPatterns-05.pdf
29/33
ObserverImplementaAon
HowtonoAfy-pproach1void ConcreteSubject::setstate(int newstate)
{
state_=newstate;
notify(); // notify all observers that // statehas changed
}
Subject s1;
subject.setstate(6);// automatic call to notify
Subject.setstate(5);
29
-
7/29/2019 designPatterns-05.pdf
30/33
ObserverImplementaAon
HowtonoAfy-pproach2void ConcreteSubject::setstate(int newstate)
{
state_=newstate;}
Subject s1;
subject.setstate(6);subject.setstate(5);
Subject.notify(); // explicit call to notify
30
-
7/29/2019 designPatterns-05.pdf
31/33
ObserverImplementaAon
thePushmodelandthePullmodelImplementaAonsoftheObserverpaZernoen
havethesubjectbroadcastaddiAonal
informaAonaboutthechange.ThesubjectpassesthisinformaAonasanargumentto
Update.
Pushmodel:thesubjectsendsoberversdetailedinformaAonaboutthechange
Pullmodel:thesubjectsendsonlyaminimalnoAficaAonandobserversaskfordetails
explicitly31
-
7/29/2019 designPatterns-05.pdf
32/33
ObserverImplementaAon
Whathappenswhenweaddnewobservers?
ImagineaddingtheabilitytosendaleZerwithcouponstocustomerslocatedwithin20milesofoneofthecompanysBrickandMortarstores.
32
-
7/29/2019 designPatterns-05.pdf
33/33
ObserverImplementaAon
Iftheclasswewanttoaddalreadyexistsandwecannotmodifyit,thenwecanadaptitasshownbelow:
33