Skip to content

Instantly share code, notes, and snippets.

@igbanam
Last active August 13, 2017 10:21
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 igbanam/0ca5d5a2ea087933592bb71671d88fb4 to your computer and use it in GitHub Desktop.
Save igbanam/0ca5d5a2ea087933592bb71671d88fb4 to your computer and use it in GitHub Desktop.
RubyConf-NG Design Patterns
# The Abstract Factory
class Waiter
def initialize meal_order
@meal_order = meal_order
end
def serve!
@meal_order.utensil
@meal_order.delicacy
end
end
# Orders
module OrderInterface
def utensil
raise 'Not implemented.'
end
def delicacy
raise 'Not implemented.'
end
end
# For completeness, we bind the orders to an OrderInterface
# A Factory
class JollofMealOrder
include OrderInterface
def utensil
puts 'Take one spoon'
end
def delicacy
puts 'Jollof for the masses'
end
end
# A Factory
class ClassyJollofMealOrder
include OrderInterface
def utensil
puts 'Take a knife, and a fork'
end
def delicacy
puts 'Jollof for the masses'
end
end
# A Factory
class AmalaMealOrder
include OrderInterface
def utensil
puts 'Chop with ya hand o jare!'
end
def delicacy
puts 'Beta Amala and Ewedu'
end
end
# First Customer waltzes in with an order
first_customer_order = ClassyJollofMealOrder.new
# ...places the order with a waiter
waiter1 = Waiter.new first_customer_order
# Waiter serves the order
waiter1.serve!
# Another customer places an order
another_customer_order = AmalaMealOrder.new
# ...places the order with a waiter
waiter2 = Waiter.new another_customer_order
# Waiter serves the order
waiter2.serve!
# This is the shoe as sold by the manufacturer
class Shoe
def cost
manufacturing_cost
end
def manufacturing_cost
40
end
end
# Same shoe in a Lekki Store
class LekkiShoe < Shoe
def cost
super * 1.23
end
end
# Same shoe at Yaba Market
class YabaShoe < Shoe
def cost
super * 0.73
end
end
# Same shoe in Dubai
class DubaiShoe < Shoe
def cost
super * 8
end
end
# any shoe in a nice KPakagee box
module KPakagee
def cost
super * 2.15
end
end
yaba_shoe = YabaShoe.new
puts yaba_shoe.cost
dubai_shoe = DubaiShoe.new
puts dubai_shoe.cost
dubai_shoe.extend(KPakagee) # dynamic way to add decorators without using inheritance
puts dubai_shoe.cost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment