2013-12-12 26 views
2

我在教科書中遇到過這個問題,但我甚至不知道代表團是什麼團隊。我知道包括什麼,但不是代表團是什麼。Ruby中的代表是什麼?

在Ruby的上下文中,將委派與包含在 中的模塊的類接口的概念進行比較。

通過模塊包含,模塊中定義的方法成爲類(及其所有子類)的接口 的一部分。 與代表團不是這種情況。

你可以用外行的話來解釋嗎?

+0

這裏有一個體面的解釋與例子:http://khelll.com/blog/ruby/delegation-in-ruby/ – lurker

+0

所以math.sqrt(10)是委託,包括數學sqrt(10)是包括? – OnTheFly

回答

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類的實例將使用A類的foo方法時,其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來回答問題。

+0

我得到這個:「這是A的問題答案:Q?」 「這裏是A的問題答案:Q?」它不應該是:「這是A的問題答案:Q?」 「這是AA對問題的回答:Q?」 – OnTheFly

+0

@OnTheFly,對不起,我犯了一個錯誤。並感謝您的回覆。 問題是'B'將使用自己的'answer_to',而不是'AA'中的。 –