加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby转发方法调用

发布时间:2020-12-17 02:58:41 所属栏目:百科 来源:网络整理
导读:我有一个生成子类实例的主类实例,这些子类需要将一些方法调用转发回主实例. 目前我的代码看起来像这样,但感觉我应该能够更有效地做同样的事情(也许使用method_missing?) class Master def initalize(mynum) @mynum = mynum end def one_thing(subinstance)
我有一个生成子类实例的主类实例,这些子类需要将一些方法调用转发回主实例.

目前我的代码看起来像这样,但感觉我应该能够更有效地做同样的事情(也许使用method_missing?)

class Master
  def initalize(mynum)
    @mynum = mynum
  end

  def one_thing(subinstance)
    "One thing with #{subinstance.var} from #{@mynum}"
  end

  def four_things(subinstance)
    "Four things with #{subinstance.var} from #{@mynum}"
  end

  def many_things(times,subinstance)
    "#{times} things with #{subinstance.var} from #{@mynum}"
  end

  def make_a_sub(uniqueness)
    Subthing.new(uniqueness,self)
  end


  class Subthing
    def initialize(uniqueness,master)
      @u = uniqueness
      @master = master
    end

    # Here I'm forwarding method calls
    def one_thing
      master.one_thing(self)
    end

    def four_things
      master.four_things(self)
    end

    def many_things(times)
      master.many_things(times,self)
    end
  end
end

m = Master.new(42)
s = m.make_a_sub("very")

s.one_thing === m.one_thing(s)

s.many_things(8) === m.many_things(8,s)

我希望你能看到这里发生了什么.我会使用method_missing,但我不知道如何应对某些调用有参数的可能性而有些没有(我不能真正重新排列Master方法的参数顺序)

谢谢阅读!

解决方法

支持委托模式

代表

Delegate在这方面有帮助吗?它允许您将方法委托给第二个类

This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.

Going a step further,the top level DelegateClass method allows you to easily setup delegation through class inheritance. This is considerably more flexible and thus probably the most common use for this library.

Finally,if you need full control over the delegation scheme,you can inherit from the abstract class Delegator and customize as needed. (If you find yourself needing this control,have a look at forwardable,also in the standard library. It may suit your needs better.)

转发

还有forwardable图书馆

This library allows you delegate method calls to an object,on a method by method basis. You can use Forwardable to setup this delegation at the class level,or SingleForwardable to handle it at the object level.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读