【发布时间】:2014-02-18 16:35:17
【问题描述】:
我的申请中有一个要处理的不同工作的列表。我正在玩弄一种使用不同类型来代表不同类型工作的设计——这是很自然的,因为它们具有不同的属性等等。对于处理,我正在考虑按照下面的代码在 C# 中使用动态关键字。
abstract class Animal {}
class Cat : Animal {}
class Dog : Animal {}
class AnimalProcessor
{
public void Process(Cat cat)
{
System.Diagnostics.Debug.WriteLine("Do Cat thing");
}
public void Process(Dog dog)
{
System.Diagnostics.Debug.WriteLine("Do Dog thing");
}
public void Process(Animal animal)
{
throw new NotSupportedException(String.Format("'{0}' is type '{1}' which isn't supported.",
animal,
animal.GetType()));
}
}
internal class Program
{
private static void Main(string[] args)
{
List<Animal> animals = new List<Animal>
{
new Cat(),
new Cat(),
new Dog(),
new Cat()
};
AnimalProcessor animalProcessor = new AnimalProcessor();
foreach (dynamic animal in animals)
{
animalProcessor.Process(animal);
}
//Do stuff all Animals need.
}
}
代码按预期工作,但是,我有一种挥之不去的感觉,我错过了一些非常明显的东西,并且有一个更好(或更广为人知)的模式可以做到这一点。
有没有更好或同等好但更被接受的模式来处理我的动物?或者,这样好吗?并且,请解释为什么任何替代方案都更好。
【问题讨论】:
-
如果您可以控制所有相关类的源代码,
dynamic在这里将是一个矫枉过正。只需将Animal.Process设为abstract方法并在派生类中覆盖它。
标签: c# design-patterns dynamic polymorphism dispatch