vendredi 18 novembre 2016

Creating new objects in a java switch statement. Alternative design pattern available?

Working on a project where the flavour of the month seems to be using switch statements and enums to decide what concrete class instance to create.

Is there an alternative design pattern that could be considered for object creation, taking into account that they all implement the same interface, but require different object parameters when creating the instance?

For example, the current code is.

SomeInterface concreteInstance;
Switch() {
  case A :
  {
     concreteInstance = new ConcreteAInstance(param1, param2);
  }

  case b : 
  {
    concreteInstance = new ConcreteBInstance(param1, param2, param3);
  }
  case c :
  {
    concreteInstance = new ConcreteCInstance(param1);
  }
}

Aucun commentaire:

Enregistrer un commentaire