dimanche 31 janvier 2021

What is the appropriate design pattern for this situation? (instance of)

I've to use a library and need to check (if this instance of that) a lot. For example:

if(myInterface instanceof Foo) {
  Foo foo = (Foo) myInterface;
  if(foo.name.equals("Alex")) {
     // use function that can handle Foo with name "Alex"
     handleAlexFooLogic(foo);
  }
  if(foo.name.equals("Michael") {
     // use function that can handle Foo with name "Michael"
     handleMichaleFooLogic(foo);
  }
}
else if(myInterface instanceof Bar) {
  Bar bar = (Bar) myInterface;
  if(bar.name.equals("Smith")) {
     // use function that can handle Bar with name "Smith"
     handleSmithBarLogic(bar);
  }
  // ...
} else if(....) {
  // ...
}

I was first thinking about the Factory pattern then I'm just stuck because something is so contradicting, that I cannot explaining.

I also want to separate the if(foo.name.equals("Name")) part to a different class, to avoid too much unpredict nested if-else

So what is the appropriate design pattern for this situation? Thank you!

Aucun commentaire:

Enregistrer un commentaire