Post on 05-Aug-2020
PatternsofCommunicationBetweenObjects
CS5010ProgramDesignParadigms"Bootcamp"Lesson10.1
1©MitchellWand,2012-2015ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.
KeyPointsforthisModule
• Objectscancommunicateintwobasicways:pullandpush.
• Objectsmusthavestableidentityinordertocommunicatereliably
• Weusestateful objectstoimplementobjectswithstableidentity.
• Publish-subscribeisacommonpatternforimplementingpush-stylecommunication
• Delegatesarearefinementofpublish-subscribe.
2
Generalization
OverConstants
OverExpressions
OverContexts
OverDataRepresentations
OverMethodImplementations
MixedData
DataRepresentations
Basics
RecursiveData
FunctionalData
Objects&Classes
Stateful Objects
Module10
3
DesignStrategies
Combinesimplerfunctions
Useatemplate
DivideintoCases
Callamoregeneralfunction
CommunicateviaState
Recuronsubproblem
KeyPointsforLesson10.1
• Sometimesyouneedtocombinedatafromtwoobjects.
• Thedatacouldbecombinedin3possibleplaces:– someexternalfunction(typicalinfunctionalorganization,butgenerallyconsideredbadOOdesign)
– askingtheotherobjecttogiveyouitsdata("pull"model)
– sendingyourinformationtotheotherobject,andaskingittodothecomputation("push"model)
4
Mostmethodshaveanobvioushome
• Mostofthetime,wewanttodocalculationsintheobjectwherethedatais.
• Ifyouneedtocomputetheareaofacircle,makethatamethodoftheCircle% class.
5
Sometimesyouneedtocombineinformationfromtwoobjects
• Howdoyoudetermineiftwoballsintersect?• Let’slookatthreedesigns.
6
Design#1: Ballsasjustdatastructures(define Ball0<%>
(interface ();; -> Integer;; RETURN: x, y coords of center and radius, all in pixelsget-xget-yget-r))
(define Ball0%(class* object% (Ball0<%>)
(init-field x y r) ; interpretation omitted...(super-new)(define/public (get-x) x)(define/public (get-y) y)(define/public (get-r) r)))
7
Design#1:Justuseobjectsinplaceofstructs.Weequipourobjectswithmethodsthatgeteachfield,anddoourcomputationoutsideofanyobject.
Hereistheinterfaceandasampleclassdefinitioninthisstyle.
Implementationoffirstdesign;; Ball0<%> Ball0<%> -> Boolean(define (intersects? b1 b2)(coordinates-intersect?(send b1 get-x) (send b1 get-y) (send b1 get-r)(send b2 get-x) (send b2 get-y) (send b2 get-r)))
(define (coordinates-intersect? x1 y1 r1 x2 y2 r2)(<=(+ (sqr (- x1 x2)) (sqr (- y1 y2)))(sqr (+ r1 r2))))
8
ThisisconsideredpoorOOdesign: wearejustusingobjectsasstructs!Wewanttopackagethecomputationwiththedata.
Design#2: Collaboratebypullinginformationfromtheotherobject
(define Ball-Pull<%>(interface ();; -> Integer;; RETURN: x, y coords of center and radius, ;; all in pixelsget-xget-yget-r
;; Ball1<%> -> Boolean;; Does the given ball intersect with this one?intersects?))
9
Inourseconddesign,weaddamethodintersects?totheinterface.
(define Ball1%(class* object% (Ball-Pull<%>)
(init-field x y r) ; interpretation omitted...(super-new);; STRATEGY: Ask the other ball for its data(define/public (intersects? other-b)(coordinates-intersect?
(send other-b get-x)(send other-b get-y)(send other-b get-r)))
;; Integer^3 -> Boolean;; GIVEN: the coordinates of some ball;; RETURNS: would that ball intersect this one?(define (coordinates-intersect? other-x other-y other-r)(<= (+ (sqr (- x other-x)) (sqr (- y other-y)))
(sqr (+ r other-r))))
(define/public (get-x) x)(define/public (get-y) y)(define/public (get-r) r)
)) 10
Asktheotherballforitsinformation
Dothecomputationhere
Bepreparedtoanswerifsomeoneasksyouthe
samequestions!
MethodDefinitionsforPullModel
Pullmodel:whathappens
1. (send b1 intersects? b2)2. b1 asksb2 foritsdata.b2 givesit.3. thenb1 doesthearithmetic.
OKifx,y,r arealreadyobservable.Butwhatiftheyarenot?
11
b1istheobjectthatactuallydoesthecomputation.
Design#3.PushModel:theobjectpushesitsdatatotheotherobject
(define Ball-Push<%>(interface ()
;; Ball-Push<%> -> Boolean;; does the given ball intersect this one?intersects?
;; Integer^3 -> Boolean;; GIVEN: the x,y,r of some ball;; RETURNS: would that ball ;; intersect with this one?intersect-responder))
12
Inthisdesign,whenthisballisaskedwhetheritintersectswithsomeotherball,itsendsitsinformationtotheotherball,andasksthatballtocomputetheintersection.
Sonowwehavetwomethods
• intersects? sendsthisball’sdatatotheotherball.
• intersect-responder respondstotherequest,computingwhetherornotthereisanintersectionbetweenthetwoballs.
13
MethodDefinitionsforpushmodel;; A Ball2 is a (new Ball2% [x Integer][y Integer][r Integer])(define Ball2% (class* object% (Ball-Push<%>)(init-field x y r) ; interpretation omitted...(super-new)
(define/public (intersects? other-b)(send other-b intersect-responder x y r))
;; Integer^3 -> Boolean;; GIVEN: the coordinates of some ball;; RETURNS: would that ball intersect this one?(define/public
(intersect-responder other-x other-y other-r)(<= (+ (sqr (- x other-x)) (sqr (- y other-y)))(sqr (- r other-r))))
))
14
Sendyourdatatotheotherballandaskhimtofinish thecomputation
Ifsomeoneasksyouaquestion, bepreparedto
answerit
Pushmodel:whathappens
1. (send b1 intersects? b2)2. b1sendsitsdatatob23. b2answersthequestion.Thisissometimescalled“doubledispatch”b2doesn’tknowwho’sasking.
15
Arelatedpatterniscalled“thevisitorpattern.”Thisisavariationofthisdesignwhenoneofthestructuresisitemizationdata.Wedon’thavetimeinthiscoursetodealwiththevisitorpattern,butyoushouldnowbeequipped tolearnaboutit.
Inthisdesign,b2 istheballthatdoesthegeometriccalculation.
Thispatternisalsosometimescalled“doubledispatch”.Itshowsupofteninobject-orientedprogramming.
Pushorpull:howtochoose?
• Mostofthetimetheanswerisclear:mostoperationsnaturallyactonaparticularobject.
• Operationsshouldhappenintheobjectwherethedataresides– ourfirstattemptwasnotgooddesign
• Binaryoperationslikeintersect?arerelativelyrareinpractice– eitherdesign2ordesign3wouldbeokforourpurposes
16
LessonSummary
• Sometimesyouneedtocombinedatafromtwoobjects.
• Thedatacouldbecombinedin3possibleplaces:– someexternalfunction(typicalinfunctionalorganization,butgenerallyconsideredbadOOdesign)
– askingtheotherobjecttogiveyouitsdata("pull"model)
– sendingyourinformationtotheotherobject,andaskingittodothecomputation("push"model)
17
NextSteps
• Study10-1-communicating-objects.rktintheExamplesfolder
• Ifyouhavequestionsaboutthislesson,askthemontheDiscussionBoard
• Thinkaboutthefollowingquestion:– Howwouldb1knowaboutb2?
• Goontothenextlesson
18