mardi 16 avril 2019

Avoid casting with a common Interface with additional methods

I have 2 classes, both having a common base class. But on top they have additional Methods that are unique to each class. They are managed in a collection of objects of the base type.

Now whenever I want to use the additional methods, I have to check for the type and cast.

How can I avoid that? So far I've come up with

  • implementing dummy Methods (and ignoring them)
  • casting (I find that not very elegant)
  • visitor pattern (but have the functionality in the visitor)

I want to find out if anybody has other ideas. (Pseudo code)

Interface CommonBase
{
    void Common method()
}

class SubClassA : CommonBase
{
    void Extra MethodA()
}

class SubClassB : CommonBase
{
    void Extra MethodB()
}

I have a list List<CommonBase>. How do I avoid casting before calling Method A/B? Or somehow executing the functionality of Method A/B?

Aucun commentaire:

Enregistrer un commentaire