我最近开始学习模式,我看到了很多像这样的策略模式的实现,但我的前辈朋友说,这是“模板方法”模式的实现。请帮助我确定适用于以下代码的设计模式:
interface IAnimal {
void MakeSound();
}
class Dog : IAnimal {
void MakeSound() {
Console.WriteLine("hoof");
}
}
class Cat : IAnimal {
void MakeSound() {
Console.WriteLine("meow");
}
}
class Cow : IAnimal {
void MakeSound() {
Console.WriteLine("moo");
}
}发布于 2021-07-13 03:57:42
这两种模式都不是;事实上,它根本不是一种模式。
策略模式将需要一个依赖于IAnimal进行其他操作的“上下文”类,而模板方法模式将使用一些公共实现代码来调用来自子类的可覆盖方法。
您的代码说明了继承的概念,它是您提到的两种模式的公共构建块。
https://stackoverflow.com/questions/68353189
复制相似问题