Is it OK to pass parameters to a Factory method?

Not only is is acceptable, but it's common to pass parameters to a factory method. Check out some examples. Normally the parameter is a type telling the factory what to make, but there's no reason you can't add other information you need to build an object. I think what you're doing is fine.


I can't see why it would be wrong to add this parameter to your factory. But be aware that you shouldn't end up adding many parameters which might not be useful to all objects created by the factory. If you do, you'll have lost quite a lot of the advantages of a factory !


The idea of a factory is that it gives you an instance of a class/interface, so there is nothing wrong with passing parameters. If there were, it would be bad to pass parameters to a new() as well.


I've seen quite a lot of examples that use a fixed set of arguments, like in your name example, and have used them myself too and i can't see anything wrong with it.

However there is a good reason that many tutorials or small articles avoid showing factories that forward parameters to the constructed objects: It is practically impossible to forward arbitrary number of arguments (even for a sane limit like 6 arguments). Each parameter you forward has to be accepted as const T& and T& if you want to do it generic.

For more complicated examples, however, you need an exponentially growing set of overloads (for each parameter, a const and a nonconst version) and perfect forwarding is not possible at all (so that temporaries are forwarded as temporaries, for example). For the next C++ Standard that issue is solved:

class ApplicationBuilder {
  template<typename... T>
  House *build( T&&... t ) {
    return new House( std::forward<T>(t)...,
                      new Kitchen(new Sink(),
                                  new Dishwasher(),
                                  new Refrigerator())
                    );
  }
};

That way, you can call

builder.build("Hello", 13);

And it will return

new House("Hello", 13, new Kitchen(new Sink(...

Read the article i linked above.