views:

797

answers:

4

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()
{
    new derived();
}

Is there any advantage to this over just having a free function:

.h file:

base* derivedFactoryFunction();

.cpp file:

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

Also: I use the abstract factory pattern for dependency injection. I might use an inheritance hierarchy based on the ABC:

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 this seems to make my code more composable, and if I wish I can wrap a real factory object in it. I can see that there may be a slight performance decrease but this is much to worry about as it is only called during startup.

+1  A: 

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

But in the second case you'll get into trouble if you want another method to go along with ther first one...

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

Then you chose.

Think Before Coding
A: 

I'd say the advantage of having the factory function as a static method within the class itself is that it is clear that it is part of the lifecycle of that class. Making it separate means other programmers who use your class would have to look somewhere else to find the factory method.

I'm sorry I'm unsure of exactly what you mean by passing around the function pointer to the factor method, but I generally wouldn't use a function pointer if you don't have to. Function pointers cannot be inlined as they cannot be resolved at compile time, which means they could possibly be slower. But besides that, it just seems bad design to use a function pointer if you can already be sure of which function you're going to call at compile time.

Ray Hidayat
+1  A: 

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

anon
+1  A: 

It depends on how flexible your factory needs to be. If the factory needs external information (like from a configuration file, program options, etc) to determine how to construct objects, than an object makes sense. If all you will ever need is in the arguments to factory, than a function is probably fine.

The only advantage I can see to having a pointer is for testing, where you can use a different factory function.

KeithB
The pointer would allow implementing the abstract factory pattern. I've expanded on it above
Will Manley