Created
May 24, 2017 08:50
-
-
Save kkempin/45764d94f587f9dea4ffefd53b463947 to your computer and use it in GitHub Desktop.
Sample code to demonstrate Visitor design pattern in Ruby
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
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