Skip to content

Instantly share code, notes, and snippets.

@samiron
Created May 9, 2010 06:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samiron/394985 to your computer and use it in GitHub Desktop.
Save samiron/394985 to your computer and use it in GitHub Desktop.
A code example of decorator pattern in Ruby. The example is taken from Head First Design Pattern book.
module AbstractBeverage
def cost
raise Exception, %Q|You should implement the cost for #{self.class}|
end
end
class DarkRoast
include AbstractBeverage
COST = 0.99
def cost
return COST
end
end
class Espresso
include AbstractBeverage
COST = 1.99
def cost
return COST
end
end
module AbstractCondiment
def cost
raise Exception, %Q|You should implement the cost for #{self.class}|
end
end
class Mocha
COST = 0.20
include AbstractCondiment
def initialize(beverage)
@beverage = beverage
end
def cost
return COST + @beverage.cost
end
end
class Whip
COST = 0.10
include AbstractCondiment
def initialize(beverage)
@beverage = beverage
end
def cost
return COST + @beverage.cost
end
end
# The darkroast
dark_roast = DarkRoast.new
#Double Mocha
dark_roast = Mocha.new(dark_roast)
dark_roast = Mocha.new(dark_roast)
# and a Whip
dark_roast = Whip.new(dark_roast)
#Ooops! how much it cost ???
puts dark_roast.cost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment