18
Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" Lesson 10.1 1 © Mitchell Wand, 2012-2015 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

PatternsofCommunicationBetweenObjects

CS5010ProgramDesignParadigms"Bootcamp"Lesson10.1

1©MitchellWand,2012-2015ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.

Page 2: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

KeyPointsforthisModule

• Objectscancommunicateintwobasicways:pullandpush.

• Objectsmusthavestableidentityinordertocommunicatereliably

• Weusestateful objectstoimplementobjectswithstableidentity.

• Publish-subscribeisacommonpatternforimplementingpush-stylecommunication

• Delegatesarearefinementofpublish-subscribe.

2

Page 3: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

Generalization

OverConstants

OverExpressions

OverContexts

OverDataRepresentations

OverMethodImplementations

MixedData

DataRepresentations

Basics

RecursiveData

FunctionalData

Objects&Classes

Stateful Objects

Module10

3

DesignStrategies

Combinesimplerfunctions

Useatemplate

DivideintoCases

Callamoregeneralfunction

CommunicateviaState

Recuronsubproblem

Page 4: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

KeyPointsforLesson10.1

• Sometimesyouneedtocombinedatafromtwoobjects.

• Thedatacouldbecombinedin3possibleplaces:– someexternalfunction(typicalinfunctionalorganization,butgenerallyconsideredbadOOdesign)

– askingtheotherobjecttogiveyouitsdata("pull"model)

– sendingyourinformationtotheotherobject,andaskingittodothecomputation("push"model)

4

Page 5: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

Mostmethodshaveanobvioushome

• Mostofthetime,wewanttodocalculationsintheobjectwherethedatais.

• Ifyouneedtocomputetheareaofacircle,makethatamethodoftheCircle% class.

5

Page 6: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

Sometimesyouneedtocombineinformationfromtwoobjects

• Howdoyoudetermineiftwoballsintersect?• Let’slookatthreedesigns.

6

Page 7: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

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.

Page 8: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

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.

Page 9: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

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.

Page 10: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

(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

Page 11: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

Pullmodel:whathappens

1. (send b1 intersects? b2)2. b1 asksb2 foritsdata.b2 givesit.3. thenb1 doesthearithmetic.

OKifx,y,r arealreadyobservable.Butwhatiftheyarenot?

11

b1istheobjectthatactuallydoesthecomputation.

Page 12: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

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.

Page 13: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

Sonowwehavetwomethods

• intersects? sendsthisball’sdatatotheotherball.

• intersect-responder respondstotherequest,computingwhetherornotthereisanintersectionbetweenthetwoballs.

13

Page 14: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

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

Page 15: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

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.

Page 16: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

Pushorpull:howtochoose?

• Mostofthetimetheanswerisclear:mostoperationsnaturallyactonaparticularobject.

• Operationsshouldhappenintheobjectwherethedataresides– ourfirstattemptwasnotgooddesign

• Binaryoperationslikeintersect?arerelativelyrareinpractice– eitherdesign2ordesign3wouldbeokforourpurposes

16

Page 17: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

LessonSummary

• Sometimesyouneedtocombinedatafromtwoobjects.

• Thedatacouldbecombinedin3possibleplaces:– someexternalfunction(typicalinfunctionalorganization,butgenerallyconsideredbadOOdesign)

– askingtheotherobjecttogiveyouitsdata("pull"model)

– sendingyourinformationtotheotherobject,andaskingittodothecomputation("push"model)

17

Page 18: Lesson 10.1 Patterns of Communication Between Objects · Patterns of Communication Between Objects CS 5010 Program Design Paradigms "Bootcamp" ... • Publish-subscribe is a common

NextSteps

• Study10-1-communicating-objects.rktintheExamplesfolder

• Ifyouhavequestionsaboutthislesson,askthemontheDiscussionBoard

• Thinkaboutthefollowingquestion:– Howwouldb1knowaboutb2?

• Goontothenextlesson

18