I've got a list of different jobs to process in my application. I'm toying with a design which uses different types to represent different types of job - this is natural because they have different properties and so on. For processing I was thinking about using the dynamic keyword in C# as per the code below.
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.
}
}
The code works as expected, but, I have a nagging feeling that I'm missing something blindingly obvious and that there's a much better (or better known) pattern to do this.
Is there any better or equally good but more accepted pattern to use to process my Animals? Or, is this fine? And, please explain why any alternatives are better.