1 of 5

CSE341: Programming Languages�Section 9

Double Dispatch, Visitor Pattern

Spring 2021

1

2 of 5

Reminders

    • Homework 5 grades will be published soon
    • Homework 6 due on Friday, May 28th, 5PM
    • Racket style guide on course website under resources

CSE 341: Programming Languages

2

3 of 5

Dispatch Overview

Dispatch is the runtime procedure for looking up which function to call based on the parameters given:

  • Racket (and Java) use Single Dispatch on the implicit this parameter
    • Uses runtime class of this to lookup the method when a call is made
    • This is what you learned in CSE 143
  • Double Dispatch uses the runtime classes of both this and a single method parameter
    • Racket/Java do not have this, but we can emulate it
  • You can dispatch on any number of the parameters and the general term for this is Multiple Dispatch or Multimethods

4 of 5

Emulating Double Dispatch

  • To emulate double dispatch in Racket just use the built-in single dispatch procedure twice!
    • Have the principal method immediately call another method on its first parameter, passing this as an argument
    • The second call will implicitly know the class of the this parameter
    • It will also know the class of the first parameter of the principal method, because of Single Dispatch

5 of 5

Double Dispatch Example: RPS

  • Suppose we wanted to code up a game of “Rock-Paper-Scissors”:
    • A game that is played in rounds with 2 players.
    • Each player gets to pick a tool: one of “Rock”, “Paper”, or “Scissors”.
  • Each combination results in a winner/loser (except when both are the same):
    • Rock beats Scissors
    • Paper beats Rock
    • Scissors beats Paper