Skip to content

Instantly share code, notes, and snippets.

@kkempin
Created May 24, 2017 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkempin/45764d94f587f9dea4ffefd53b463947 to your computer and use it in GitHub Desktop.
Save kkempin/45764d94f587f9dea4ffefd53b463947 to your computer and use it in GitHub Desktop.
Sample code to demonstrate Visitor design pattern in Ruby
module Visitable
def accept(visitor)
visitor.visit(self)
end
end
class Product
include Visitable
attr_reader :name, :price
def initialize(name:, price:)
@name = name
@price = price
end
end
class Order
include Visitable
def initialize
@products = []
end
def add_product(product)
@products << product
end
def accept(visitor)
@products.each do |product|
product.accept(visitor)
end
end
end
class Visitor
def visit(subject)
raise NotImpelementedError.new
end
end
class ProductsPrinterVisitor < Visitor
def visit(subject)
puts "Product: #{subject.name} - $#{subject.price}"
end
end
class HalfPriceSimulatorVisitor < Visitor
def visit(subject)
puts "Product: #{subject.name} - after 50% discount: $#{subject.price / 2.0}"
end
end
p1 = Product.new(name: 'Laptop', price: 1000)
p2 = Product.new(name: 'Beer', price: 5)
order = Order.new
order.add_product(p1)
order.add_product(p2)
order.accept(ProductsPrinterVisitor.new)
order.accept(HalfPriceSimulatorVisitor.new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment