Created
May 9, 2010 06:40
-
-
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.
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 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