开发者

how can I implement factory pattern using C++ class?

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 fact开发者_如何学编程ory pattern works in C++. Can anybody suggest good sample program or link for the same.

Thanks

krissam


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜