How to resolve the dilemma when a factory needs to create objects with multiple common parameters?

Rui :

I have a set of subclasses of PageRenderer abstract class, e.g.

  • ImagePageRenderer
  • TextPageRenderer
  • VideoPageRenderer.

So in order to get the PageRenderer instance, a factory method is suitable. The concreate factory looks like this:

public class PageRendererFactory extends AbstractFactory {
  PageRenderer createPageRenderer(Type type) {
    //implementation
  }
}//Code AbstractFactory is skipped here

However, the problem is that the PageRenderer contains several instance variables for the subclasses to use:

public abstract class PageRenderer {
  protected A a;
  protected B b;
  protected C c;
  protected D d;
  Protected E e;
  //there might be even more instance variables
}

and all the subclasses of PageRenderer share these instance variables.

According to the conditions above, I would change the PageRendererFactory so that it contains the mentioned instance variables:

public class PageRendererFactory extends AbstractFactory {
  private A a;
  private B b;
  private C c;
  private D d;
  Private E e;
  //there might be even more instance variables here
  PageRenderer createPageRenderer(Type type) {
    //use the instance variables to instantiate the subclass of PageRenderer according to the Type
  }
}//Code AbstractFactory is skipped here

Question: In this case, I probably need setters on this PageRendererFactory, but then this factory seems to be mixed with the builder pattern! So is this a good solution? or is there any better alternative for this solution?

Bor Laze :

You decision to use Factory is correct.

And there doesn't matters, how this Factory will be created.

By direct call

Factory factory = new Factory();

By direct call with setters

Factory factory = new Factory();
factory.setA(a);
...
factory.setE(e);

By call with parameters

Factory factory = new Factory(a, b, c, d, e);

Or via builder

Factory factory = new Factory.Builder()
    .withA(a)
    ...
    .withE(e)
    .build();

Like for me, constructor with parameters is preferable because it prevents you from missing one or more internal fields.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=160571&siteId=1