lundi 23 mai 2016

Something like factory pattern with inheritance

I am looking for solution for following problem:

class FooClient{
  private FooProvider provider;

  public setProvider(FooProvider provider){...}

  public void doSomeTask(){
    Foo foo =provider.getFoo();
  }
}

I find this code good because I can easy test FooClient, passing mock of provider. Besides provider does all the work about initializing foo. The problem is that creating different clients (i.e. it can be in many situations) I may need to make new subclasses of Foo. The only solution which came to my mind is something like this:

class FooClient{
  private FooProvider provider;

  public setProvider(FooProvider provider){...}

  public void doSomeTask(){
    FooSubclass foo =new FooSubclass();
    provider.initialize(foo);
  }
}

However, in this case testing becomes difficult. Is there a solution/pattern for get FooSubclass instance from provider without using reflection?

Aucun commentaire:

Enregistrer un commentaire