Created
August 13, 2013 18:11
-
-
Save joonyou/6223962 to your computer and use it in GitHub Desktop.
code from visitor pattern screencast
This file contains 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 Goodie | |
attr_accessor :price | |
def initialize(price) | |
@price = price | |
end | |
def accept(visitor) | |
visitor.visit(self) | |
end | |
end | |
class TaxManVisitor | |
def initialize(rate) | |
@rate = rate / 100.0 | |
end | |
def visit(obj) | |
if obj.respond_to? :price | |
obj.instance_eval { class << self; attr_accessor :tax; end } | |
obj.tax = obj.price * @rate | |
end | |
end | |
end | |
x = Goodie.new(25) | |
puts "price is #{x.price}" | |
x.accept TaxManVisitor.new(9) | |
puts "tax is #{x.tax}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment