views:

78

answers:

3

Hi, I am working on a project which was mostly implemented using factory and facade patterns. However I am unable to understand as I do not have a clear concepts of how factory pattern works in C++. Can anybody suggest good sample program or link for the same.

Thanks

krissam

+1  A: 

The factory pattern works in all languages the same.

class NodeFactory {
   SimpleNode createSimple() { return new SimpleNode(); }
   ComplexNode createComplexNode() { return new ComplexNode(); }
};

A factory is just a class that has methods which create objects.

Angelo

Angel O'Sphere
Shouldn't these be class (`static`) methods rather than instance methods? You shouldn't have to instantiate a Factory object to create other nodes.
Seth Johnson
No, that would completely spoil the point of having a factory. You use a factory for two purposes. 1) the constructors of the objects you want are not good enough. e.g.
Angel O'Sphere
No, that would completely spoil the point of having a factory. You use a factory for two purposes. 1) the constructors of the objects you want are not good enough. So you need to call several set methods to finally get the object into a good state. This is cumbersome and you easy make a mistake. So you put object creation and proper initialization into a factory. 2) you dont really know what exact objects you need to create. In my previous example you can make a derived Factory. That creates EvenMoreComplexNodes and EvenSimplerSimpleNodes. Assuming those classes are derived from the other ones
Angel O'Sphere
+2  A: 

A good website for all design pattern queries is Hudson Design Patterns

It pretty much has all GOF design patterns in it, but explains it in a way which is quite easy to understand. Also includes demos.

Craig
Link provided is quite informative :)
Koteswara sarma
Its good link and vast stuff about design patterns
krissam
+1  A: 

Wikipedia has a factory pattern page.

For simple cases there really is no trick. Just

Foo* createFoo() {
  return new Foo();
}

It gets trickier when you want to do more than just use new. One good example is if the constructor takes a number of parameters, or if the objects need to be initialized somehow. In that case you can load up the factory with the requirements and not make the developer worry about them:

class BarFactory {
    BarFactory(Dep* x, Depen* y) ...

    getBar() {
       return new Bar(x->SOME_METHODS, y->SOMETHINGELSE, ...);
    }

}

In that example the the factory takes the confusion out of correctly making a Bar object, (imagine it took more arguments and they needed a lot of hand holding). This can be helpful when you've got an API with a lot of options that don't change or just a bad API.

Paul Rubel