mardi 12 juin 2018

Factory pattern for compile time

I am trying to figure out the right design for this problem

I have three classes T, C and E (Thread, Consumer, and Event)

public class T {
  private C _c = new C();
}

public class C {
  private someMenthod() {
    E e = new E();
    // do something with e
  }
}

In my "main" T is created and its dependencies are encapsulated

T t = new T();

Now the design has changed and we need multiple Cs and each one of them should construct a different E. The code is same for all so I don't need to change C

I tried to do it with generics, as it looks like this is a simple and clean way. However, it looks like it is not possible to use new on generic type. (Misguided by C++ templates)

public class T<K extends E> {
  private C _c = new C<K>();
}

public class C<K extends E> {
  private someMenthod() {
    E e = new K();
  }
}

My other option is to pass some kind of compile time factory

public interface IEFactory {
    public E create();
}

public class EFactory implements IEFactory{
  public E create() {
    return new E1();
 }
}

public class T {
  private C _c;

  public T(IFactory _factory) {
     _c = new C(_fcatory);
  }
}

public class C {
  private IFactory _factory;

  public C(IFactory factory) {
     _factory = factory;
  }

  private someMenthod() {
    E e = _factory.create();
  }
}

This solution feels less elegant passing the factory all the way down. Is there a better and more elegant way approaching this?

Aucun commentaire:

Enregistrer un commentaire