Ruby 中的委托是什么?

3

我在我的教科书中看到了这个词,但我甚至不知道什么是委托。我知道什么是包含,但不知道什么是委派。

就 Ruby 的语境而言,从类接口的概念来比较委派和模块包含。

使用模块包含时,定义在模块中的方法会成为类(以及它们所有的子类)的接口的一部分。这在委派中并不是这种情况。

您能用通俗易懂的语言解释一下吗?


这里有一个不错的解释和示例:http://khelll.com/blog/ruby/delegation-in-ruby/ - lurker
那么 math.sqrt(10) 是委托,而 include math sqrt(10) 是包含? - OnTheFly
2个回答

5

委托简单来说,就是一个对象使用另一个对象来调用方法。

如果你有以下代码:

class A
  def foo
    puts "foo"
  end
end

class B
  def initialize
    @a = A.new
  end

  def bar
    puts "bar"
  end

  def foo
    @a.foo
  end
end

B类的一个实例在调用它的foo方法时会使用A类的foo方法。换句话说,B类的实例将foo方法委托给A类。


2
class A
  def answer_to(q)
    "here is the A's answer to question: #{q}"
  end
end

class B
  def initialize(a)
    @a = a
  end
  def answer_to(q)
    @a.answer_to q
  end
end

b = B.new(A.new)

p b.answer_to("Q?")


module AA
  def answer_to(q)
    "here is the AA's answer to question: #{q}"
  end
end

class BB
  include AA
end

p BB.new.answer_to("Q?")

B将问题委托给A,而BB使用模块AA来回答问题。


我得到了这个:“这是A对问题Q的答案?” “这是A对问题Q的答案?”难道不应该是:“这是A对问题Q的答案?” “这是AA对问题Q的答案?” - OnTheFly
@OnTheFly,抱歉我犯了一个错误。感谢您的回复。 问题是B将使用自己的answer_to,而不是AA中的那个。 - Windor C

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接