Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Double dispatch
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Ruby=== A common use case is displaying an object on a display port which can be a screen or a printer, or something else entirely that doesn't exist yet. This is a naive implementation of how to deal with those different media. <syntaxhighlight lang="ruby"> class Rectangle def display_on(port) # selects the right code based on the object class case port when DisplayPort # code for displaying on DisplayPort when PrinterPort # code for displaying on PrinterPort when RemotePort # code for displaying on RemotePort end end end </syntaxhighlight> The same would need to be written for Oval, Triangle and any other object that wants to display itself on a medium, and all would need to be rewritten if a new type of port were to be created. The problem is that more than one degree of polymorphism exist: one for dispatching the display_on method to an object and another for selecting the right code (or method) for displaying. A much cleaner and more maintainable solution is then to do a second dispatch, this time for selecting the right method for displaying the object on the medium: <syntaxhighlight lang="ruby"> class Rectangle def display_on(port) # second dispatch port.display_rectangle(self) end end class Oval def display_on(port) # second dispatch port.display_oval(self) end end class DisplayPort def display_rectangle(object) # code for displaying a rectangle on a DisplayPort end def display_oval(object) # code for displaying an oval on a DisplayPort end # ... end class PrinterPort def display_rectangle(object) # code for displaying a rectangle on a PrinterPort end def display_oval(object) # code for displaying an oval on a PrinterPort end # ... end </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)