I have a list of different jobs to handle in my application. I play with a design that uses different types to represent different types of work - this is natural because they have different properties, etc. For processing, I was thinking about using the dynamic keyword in C # according to 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);
}
}
}
The code works as expected, but I feel like I have something dazzlingly obvious and that there is a much better (or better known) template for this.
Is there any better or equally good, but more acceptable template for handling my animals? Or is it beautiful? And please explain why all alternatives are better.