论坛首页 编程语言技术论坛

Ruby库中委托Delegator类的实现

浏览 1830 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-10-14  
委托的模式上一篇偷天换日已经解释,这里只讲解里面的Delegator库的实现.

既然采用ruby,它的库一般来说,用起来会更加funny,更加自然.
如同singleton单例库,你写一个类
class Klass
 def method
 end
end

想让它成为单例类,只需:
require 'singleton'
class Klass
 include Singleton
 def method
 end
end

如此简单,它自动将构造方法置为隐藏,自动加载多线程锁调用,哇,还是线程安全,如果是自己写那得不少代码,而且使用ruby的Module机制,无须继承任何类,毫无副作用...

好了,题外话讲完后,我们来看看Delegator吧.
打开ruby库的delegate.rb文件.
代码行有多少,好家伙,大概330行.除去注释,实际有效代码有100行吧.
第1步看看使用接口先:
# SimpleDelegator's implementation serves as a nice example here.
#
#    class SimpleDelegator < Delegator
#      def initialize(obj)
#        super             # pass obj to Delegator constructor, required
#        @_sd_obj = obj    # store obj for future use
#      end
# 
#      def __getobj__
#        @_sd_obj          # return object we are delegating to, required
#      end
# 
#      def __setobj__(obj)
#        @_sd_obj = obj    # change delegation object, a feature we're providing
#      end
# 
#      # ...
#    end

这就是说只要继承Delegator,然后实现__getobj__与__setobj__方法即可.
这个使用方法在上一篇偷天换日中即用这个方法.
想想也是,如此的接口也很简洁了.
再看如何实现的:
class Delegator

  #
  # Pass in the _obj_ to delegate method calls to.  All methods supported by
  # _obj_ will be delegated to.
  #
  def initialize(obj)
    #拿到所有类的实例方法,去掉几个
    #因为Kernel是一个module,它会被所有类包含.可参阅RubyHackGuide进行掌握.
    preserved = ::Kernel.public_instance_methods(false)
    preserved -= ["to_s","to_a","inspect","==","=~","==="]
    for t in self.class.ancestors
      preserved |= t.public_instance_methods(false)
      preserved |= t.private_instance_methods(false)
      preserved |= t.protected_instance_methods(false)
      break if t == Delegator
    end
    preserved << "singleton_method_added"
    for method in obj.methods
      # 搜集到所有实例方法,
      # 以下开始利用eval动态往本代理中添加方法
      next if preserved.include? method
      begin
       # 这里的self是实例本身,不是类,请注意.
       # 所以定义的方法都是自身可以用,而不是整个委托类.
       # 异常处理的时候使用了一个的技巧,将委托的异常信息给去掉了,更加透明了...(好阴啊,如果是库出问题了连个跟踪的地儿都找不到)
	eval <<-EOS
	  def self.#{method}(*args, &block)
	    begin
	      __getobj__.__send__(:#{method}, *args, &block)
	    rescue Exception
	      $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
	      $@.delete_if{|s| /^\\(eval\\):/ =~ s}
	      Kernel::raise
	    end
	  end
	EOS
      rescue SyntaxError
        raise NameError, "invalid identifier %s" % method, caller(4)
      end
    end
  end
  alias initialize_methods initialize

  # 这个method_missing是重新实现是怕被委托的那小子动态添加方法,那'我'(委托类)不能不支持啊,所以添加在这里.
  # 那我想问原作者,你上述的实现期不多余了,就只为能再透明点啊...
  # Handles the magic of delegation through \_\_getobj\_\_.
  def method_missing(m, *args)
    target = self.__getobj__
    unless target.respond_to?(m)
      super(m, *args)
    end
    target.__send__(m, *args)
  end

  # 
  # Checks for a method provided by this the delegate object by fowarding the 
  # call through \_\_getobj\_\_.
  # 
  def respond_to?(m)
    return true if super
    return self.__getobj__.respond_to?(m)
  end

  #
  # This method must be overridden by subclasses and should return the object
  # method calls are being delegated to.
  #
  # 你继承了后老实实现它吧.
  def __getobj__
    raise NotImplementedError, "need to define `__getobj__'"
  end

  # 这些为了可以使用marshal进行外部类存储.
  # 如果不使用它,完全不用理会.
  # Serialization support for the object returned by \_\_getobj\_\_.
  def marshal_dump
    __getobj__
  end
  # Reinitializes delegation from a serialized object.
  def marshal_load(obj)
    initialize_methods(obj)
    __setobj__(obj)
  end
end


所有的解析在上面的注释里了.
这里需要你的ruby技术相当熟练,掌握ruby元编程技能.因能力有限,欢迎就不同的观点进行探讨.
写在这里后,据松本行弘说forwardable模块更加优秀.有时间可以再研究下.
最后抱怨一下,ruby库的测试不完善啊,偶尔会出现一些问题,还需要进行猴子补丁..
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics