require 'delegate'
class Assistant
def initialize(name)
@name = name
end
def read_email
puts "(#{@name}) It's mostly spam."
end
def check_schedule
puts "(#{@name}) You have a meeting today."
end
end
class Manager < DelegateClass(Assistant)
def initizlize(assistant)
super(assistant)
end
def attend_meeting
puts "please hold my calls"
end
end
frank = Assistant.new("Frank")
anne=Manager.new(frank)
anne.attend_meeting #=> please hold my calls
anne.read_email #=>(Frank) It's mostly spam.
anne.check_schedule #=>(Frank) You have a meeting today.
=begin
DelegateClass()是一种拟态方法,这种方法创建并返回一个新的Class..这个类会定义一个method_()方法,并把对它发生的调用转发到被封装的对象上,比如本例的Assistant对象. Manager类会继承这个method_missing()方法,因此它就成为被封装对象的一个代理.结果,Manager就会把自己无法识别的方法转发给它封装的Assistant.
=end