Created
October 7, 2011 08:55
-
-
Save JulesWang/1269820 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Decorator | |
def initialize(decorated) | |
@decorated = decorated | |
end | |
def method_missing(method,*args) | |
# empty? is a method; ?: is a tri-operator | |
args.empty? ? @decorated.send(method):@decorated.send(method,args) | |
end | |
# Decorator does not change the nature of object it decorates; | |
def kind_of?(name) | |
@decorated.kind_of?name | |
end | |
end | |
class Coffee | |
def cost | |
2 | |
end | |
def taste | |
p "taste good!" | |
end | |
end | |
class Milk | |
include Decorator | |
def cost | |
@decorated.cost+0.4 | |
end | |
end | |
class Whip | |
include Decorator | |
def cost | |
@decorated.cost+0.2 | |
end | |
end | |
my_coffee = Whip.new(Milk.new(Coffee.new)) | |
p my_coffee.cost; | |
p my_coffee.kind_of?Coffee | |
my_coffee.taste | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment