I came across this in my textbook, but I don't even know what delegation is. I know what inclusion is, but not what delegation is.

In the context of Ruby, compare delegation to module inclusion in terms of the notion of class interfaces.

With module inclusion, methods defined in modules become part of the interface of classes(and all their subclasses). This is not the case with delegations.

Can you explain in layman's terms?

有帮助吗?

解决方案

Delegation is, simply put, is when one object uses another object for a method's invocation.

If you have something like this:

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

An instance of the B class will utilize the A class's foo method when its foo method is called. The instance of B delegates the foo method to the A class, in other words.

其他提示

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 delegate the question to A, while BB use module AA to answer question.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top