vendredi 7 octobre 2016

Casting an interface type to an implementing class

My question involves the below example I've provided. I feel like this is an anti pattern. Not sure if it has a name. What I would like to is be able to access the specific implementations. Attempting to avoid answers that may just be an opinion whether this pattern is bad/good, I would like to know of a better way to reconsider this problem, and if there is a name for this (anti)pattern.

interface WTF
{
  Type type;
}

enum Type
{
  A,
  B
}

interface A : WTF
{
  Type type = Type.A;

  void MethodA();
}

interface B : WTF
{
  Type type = Type.B;

  void MethodB();
}



void Foo(List<WTF> list)
{
  foreach(var i in list)
  {
    switch(i.type)
    {
      case Type.A:
        A a = (A)i;
        a.MethodA();
        break;
      case Type.B:
        B b = (B)i;
        b.MethodB();
        break;
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire