Ruby支持「包含多態性」嗎?這與鴨打字相同嗎?Ruby支持包含多態性嗎
如果不是,多態性和Ruby中的鴨子打字有什麼區別?
可有人請與下面我舉個例子說明:
# superclass - inheritance
class Animal
def make_noise
# define abstarct method (force override)
raise NoMethodError, "default make_noise method called"
end
end
# module - composition
module Fur
def keep_warm
# etc
end
end
# subclass = is-a relationship
class Bird < Animal
# override method - polymorphism
def make_noise
"Kaaw"
end
end
class Cat < Animal
# module mixin = has-a relationship
include Fur
def make_noise
"Meow"
end
end
class Radio
# duck typing (no inheritance involved)
def make_noise
"This is the news"
end
end
class Coat
include Fur
end
animals = [Bird,Cat,Radio,Coat,Animal]
animals.each do |a|
# polymorphism or duck typing?
obj = a.new
if obj.respond_to? 'make_noise'
puts obj.make_noise
end
end
我的例子做出了我想確認的假設。例如,多態性僅限於使用繼承的地方。鴨子打字說明mixin。我在解決這個問題時遇到了麻煩,似乎存在來自書籍/ wikipedia等的衝突信息。 – Question 2010-12-17 16:03:48