Ruby中的委托是什么?

OnT*_*Fly 3 ruby delegation

我在教科书中遇到过这个问题,但我甚至不知道代表团是什么.我知道包含是什么,但不知道代表团是什么.

在Ruby的上下文中,根据类接口的概念将委托与模块包含进行比较.

使用模块包含,模块中定义的方法将成为类(及其所有子类)接口的一部分.各代表团的情况并非如此.

你能用外行的话解释一下吗?

Zaj*_*ajn 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
Run Code Online (Sandbox Code Playgroud)

foofoo调用其方法时,B类的一个实例将使用A类的方法.换句话说,Bfoo方法委托给A类的实例.