【Ruby】DelegateClass

Ruby里如果要Mixin的一个Module很简单

class Test 
  include Module1
end

但之前没有思考过能不能Mixin一个Class的功能? 答案是:可以,使用DelegateClass

require 'delegate'

class Assistant
  def initialize(name)
    @name = name
  end 

  def read_email
    "(#{@name}) It is mostly spam."
  end
end

class Manager < DelegateClass(Assistant)
  def initialze(assistant)
     super(assistant)
  end 
  def attend_meeting
    puts "please hold my call"
  end 
end 

assistant= Assistant.new("Bill Gate") mgr
= Manager.new(assistant) mgr.read_email #(Bill Gate) It is mostly spam. mgr.attend_meeting # please hold my call

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/delegate/rdoc/Object.html

posted @ 2013-05-08 14:32  卜海清  阅读(316)  评论(0编辑  收藏  举报