Factory object vs Factory function

I have an ABC with several derived classes. To create these derived classes, I use the factory pattern:

.h file:

class derivedFactory { public: base* createInstance(); }; 

.cpp file:

 base* derivedFactory::createInstance() { return new derived(); } 

Are there any advantages to this just having a free function:

.h file:

 base* derivedFactoryFunction(); 

.cpp file:

 base* derivedFactoryFunction() { return new derived(); } 

Also: I use the abstract factory pattern to inject dependencies. I could use the ABC based inheritance hierarchy:

 class objectCreator { public: base* create() = 0; }; 

Is there any advantage to using this over a function pointer:

 boost::function<base* ()> factory_ptr; 

Using boost :: bind / lambda seems to make my code more complex, and if I want, I can wrap a real factory object in it. I see that there may be a slight decrease in performance, but there is a lot to worry about, since it is called only during startup.

+6
c ++ design-patterns factory
source share
4 answers

It depends on how flexible your factory should be. If the factory requires external information (for example, from a configuration file, program parameters, etc.), to determine how to create objects, than an object makes sense. If all you ever need is in the factory arguments, than the function is probably fine.

The only advantage I can see in the pointer is testing, where you can use another factory function.

+2
source share

Having an interface with a single method or method pointer is equivalent.

But in the second case, you will run into a problem if you want another method to match the first ...

And the interface is more readable than the method pointer, in my opinion.

Then you have chosen.

+1
source share

I would say that the advantage of the factory function as a static method inside the class itself is that it is clear that it is part of the life cycle of this class. Sharing this, other programmers who use your class should look elsewhere to find the factory method.

I'm sorry that I'm not sure what you mean by skipping the function pointer to the factor method, but I didn't use the function pointer at all if you don't need it. Function pointers cannot be inlined since they cannot be resolved at compile time, which means they can be slower. But beyond that, it just seems like a bad design uses a function pointer if you can already be sure which function you are going to call at compile time.

+1
source share

Do you ever want more than one factory for a type? If so, you need factory objects.

+1
source share

All Articles