在 C# 中,我可以这样做:
class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach (Animal a in animals)
{
Console.WriteLine(a.MakeNoise());
a.Sleep();
}
}
}
public class Animal
{
public virtual string MakeNoise() { return String.Empty; }
public void Sleep()
{
Console.Writeline(this.GetType().ToString() + " is sleeping.");
}
}
public class Dog : Animal
{
public override string MakeNoise()
{
return "Woof!";
}
}
public class Cat : Animal
{
public override string MakeNoise()
{
return "Meow!";
}
}
显然,输出是(稍微解释一下):
由于 C# 经常因其冗长的类型语法而受到嘲笑,因此如何在鸭子类型语言(例如 Ruby)中处理多态性/虚拟方法?
到目前为止所有的答案对我来说看起来都很好。我想我只是提到整个继承的事情并不是完全必要的。暂时排除“睡眠”行为,我们可以使用鸭子类型实现整个期望的结果,并且根本不需要创建 Animal 基类。谷歌搜索“鸭子打字”应该会产生很多解释,所以在这里我们只说“如果它像鸭子一样走路并且像鸭子一样嘎嘎叫……”
“睡眠”行为可以通过使用 mixin 模块来提供,例如 Array、Hash 和其他 Ruby 内置类(包括 Enumerable)。我并不是说它一定更好,只是一种不同的、也许更惯用的 Ruby 方式。
module Animal
def sleep
puts self.class.name + " sleeps"
end
end
class Dog
include Animal
def make_noise
puts "Woof"
end
end
class Cat
include Animal
def make_noise
puts "Meow"
end
end
剩下的你都知道...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)