creational pattern for instances depending on multiple subclass instances

Posted by markusw on Stack Overflow See other posts from Stack Overflow or by markusw
Published on 2014-06-01T09:08:24Z Indexed on 2014/06/01 9:25 UTC
Read the original article Hit count: 265

Filed under:
|

I have a problem, for that I was not able to identify a suitable design pattern.

I want to create instances depending on a given type that has been passed to a factory method. What I am doing until now is the following:

T create(SuperType x) {
  if (x instanceof SubType1) {
    // do some stuff and return a new SubType extends T
  } else if (x instanceof SubType2) {
    // do some stuff and return a new SubType extends T
  } else if ...

  } else {
    throw new UnSupportedOperationException("nothing defined for " + x);
  }
}

It seems not to be best pratice for me.

Has anybody an idea how to solve this in a better way?

© Stack Overflow or respective owner

Related posts about java

Related posts about design-patterns