0
相对于继承,修饰的好处是不需要像继承一样创建很多方法,直接就可以转到原始对象上去。
Posted on
Friday, August 25, 2017
by
醉·醉·鱼
and labeled under
ruby
修饰,是设计模式里面提到的,不影响原始的对象,给对象附上多个组件,让其能够支持多个方法。https://robots.thoughtbot.com/evaluating-alternative-decorator-implementations-in提到了几种方法,对比了一下,觉得SimpleDelegator还不错。对于简单的case,还可以直接用Forwardable。相对于继承,修饰的好处是不需要像继承一样创建很多方法,直接就可以转到原始对象上去。
require 'delegate'
class Coffee
def cost
2
end
def origin
"Colombia"
end
end
module DecoratorClass
def class
__getobj__.class
end
end
class Milk < SimpleDelegator
include DecoratorClass
def cost
super + 0.4
end
end
class Sugar < SimpleDelegator
include DecoratorClass
def cost
super + 0.2
end
end
p Milk.ancestors
coffee = Coffee.new
p Sugar.new(Milk.new(coffee)).cost # 2.6
p Sugar.new(Sugar.new(coffee)).cost # 2.4
p Milk.new(coffee).origin # Colombia
p Sugar.new(Milk.new(coffee)).class # Coffee
Post a Comment