I'm not clear about where to put the if
/switch
when choosing what implementation/subclass to instantiate, specially when considering that now interfaces can have static methods.
Let's say I have a service, a type defined by an interface and a couple of implementations. I guess that it'd be better not to put that logic in the service, but to have factory method. But should it go in the interface or in another class with a param-to-type map as suggested in this answer?
It seems natural to me to put it in the interface:
public interface MyInterface
{
public void doSomething();
public static MyInterface create(int param)
{
if (param == 0)
return new ImplA();
else
return new ImplB();
}
}
and then just simply call it from the service:
public class MyService
{
public void serveMe(int param)
{
MyInterface.create(param).doSomething();
}
}
But I don't know if it's bad having the interface knowing about its implementation, or a parent class knowing about its subtypes. So
- Where should I put that logic?
- Would that change a lot if I'm choosing subclasses of a type?