I've seen similar questions/answers for this posted in the past, but mine differs slightly from the others that I've seen.
Essentially, I have a common interface and several classes that implement/inherit from it. Then, in a separate class, I have methods that must act upon objects given by the interface IObject. However, each of them must be acted upon in different ways, hence why there is a separate declaration of the method for each concrete type that extends IObject.
class IObject
{
...
}
class ObjectType1 : IObject
{
...
}
class ObjectType2 : IObject
{
...
}
class FooBar
{
void Foo (ObjectType1 obj);
void Foo (ObjectType2 obj);
}
Now, to me, one obvious solution is to take advantage of dynamic binding by placing the method Foo inside each individual class, which would automatically choose at runtime the correct Foo to execute. However, this is not an option here, because I am defining multiple models for how to act upon these objects, and I would rather encapsulate each individual model for handling objects in its own class, rather than stuff all of the models into the object classes.
I found this post which shows how to use a dictionary to dynamically choose at runtime the correct method implementation. I'm fine with this approach; however, suppose that I have to perform a dispatch like this once in every model. If I only have IObject and its concrete implementations, is there any way to generalize this approach so that I could call methods of any name based on the runtime type of the objects?
I know this is probably an unclear question, but I would greatly appreciate any help.