1

Suppose there is a factory as below. I would like to know if it is possible not to include ObjectA.h and ObjectB.h.

directory structure
factory

|-----ObjectA

|-----ObjectB

Since I don't want to include the header file in the sub-directory, is there any way to do so? And if there is a new objectC, it does not need to modify the factory class. it will automatically create ObjectC if the type is "TypeC".

#include "ObjectA.h"
#include "ObjectB.h"

object* create(const string& type)
{
    if (type == "typeA")
    {
       return new ObjectA();
    }
    else
    {
       return new ObjectB();
    }
};
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
Michael D
  • 1,449
  • 5
  • 18
  • 31
  • This could be useful for you, take a look here http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus and here http://stackoverflow.com/questions/8719119/bad-practice-to-return-unique-ptr-for-raw-pointer-like-ownership-semantics – rsc Jul 13 '12 at 06:44
  • Thanks. It is really helpful. However, the register function call is in the contructor of the factory. I am just wondering if it is possbile to put it in the concrete class. – Michael D Jul 13 '12 at 09:01

1 Answers1

1

Yes, separate the implementation to an implementation file and only include the files there, providing solely the function prototype in the header.

To actually call new ObjectA(); and new ObjectB(); you have to include the definitions in the calling site.

//factory.h
object* create(const string& type);

//factory.cpp
#include "factory.h"
#include "ObjectA.h"
#include "ObjectB.h"

object* create(const string& type)
{
    if (type == "typeA")
    {
       return new ObjectA();
    }
    else
    {
       return new ObjectB();
    }
};
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • this code could be much improved if the factory contained a registry and all `object` derived classes were registered prior to use. This would eliminate the `if-else` or `switch` inside the factory function. – TemplateRex Jul 13 '12 at 06:36
  • @rhalbersma - I used to think this too.. But the price you pay is some kind of global object / singleton - and that can lead to all kinds of other pain later. IMO updating a single file is a cheaper price to pay.. or you can generate that factory .cpp file as part of your build process. – Michael Anderson Jul 13 '12 at 06:46
  • @MichaelAnderson You don't have to use singletons/globals for factories. You can also store the registry in objects on the stack, or -as is typically is the case- if you need to let a factory live longer than the scope it is used in, you can wrap it in a shared_ptr. – TemplateRex Jul 13 '12 at 08:36
  • @rhalbersma - Agreed - I (mistakenly) thought you were talking about the automatic registration trick that people sometimes try to use to add constructors to the registry within the factory. – Michael Anderson Jul 13 '12 at 08:54