Created
July 10, 2013 19:52
-
-
Save david-hodgetts/5969640 to your computer and use it in GitHub Desktop.
double dispatch in ruby -> http://blog.bigbinary.com/2013/07/07/visitor-pattern-and-double-dispatch.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node | |
def accept visitor | |
raise NotImplementedError.new | |
end | |
end | |
module Visitable | |
def accept visitor | |
visitor.visit self | |
end | |
end | |
class IntegerNode < Node | |
include Visitable | |
attr_reader :value | |
def initialize(value) | |
@value = value | |
end | |
end | |
class StringNode < Node | |
include Visitable | |
attr_reader :value | |
def initialize(value) | |
@value = value | |
end | |
end | |
class Ast < Node | |
def initialize | |
@nodes = [] | |
@nodes << IntegerNode.new(2) | |
@nodes << IntegerNode.new(3) | |
end | |
def accept visitor | |
@nodes.each do |node| | |
node.accept visitor | |
end | |
end | |
end | |
class BaseVisitor | |
def visit subject | |
method_name = "visit_#{subject.class}" | |
send(method_name, subject) | |
end | |
end | |
class DoublerVisitor < BaseVisitor | |
def visit_IntegerNode(subject) | |
puts subject.value * 2 | |
end | |
def visit_StringNode(subject) | |
puts subject.value.to_i * 2 | |
end | |
end | |
Ast.new.accept(DoublerVisitor.new) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment