Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

proper factory pattern in C++

in C# you have to declare everything in a class so an example factory pattern could look like:

namespace MySpace {

public class CFactory
{
  public static CFactory Current()
  {
    static CFactory singleton;
    return singleton;
  }
  public CBase Create() { return null; }
}

}

in C++ you dont have this limitation.. So is it considered "bad practice" to have "factory" methods be global functions vs having them be a class?

example 1:

namespace MySpace {

// factory method
std::shared_ptr<CBase> CreateBase() { return NULL; }

}

example 2:

namespace MySpace {

// factory class
class CFactory
{
public:
  std::shared_ptr<CBase> CreateBase() { return NULL; }
};

// factory method exposing class
CFactory& GetFactory()
{
  static CFactory singleton;
  return singleton;
}

}

example 3:

namespace MySpace {

// factory class with no global function
class CFactory
{
public:
  std::shared_ptr<CBase> CreateBase() { return NULL; }

public:
  static CFactory& getFactory()
  {
     static CFactory singleton;
     return singleton;
  }
};

}

the std library uses a lot of global functions for "factory methods".. an example of this would be std::make_shared.

I have used both before and I am just not sure if one is considered "better" over the other

like image 941
BabelFish Avatar asked Oct 14 '22 17:10

BabelFish


1 Answers

You can presume from its usage in the standard library that a namespaced global factory is not implicitly wrong. Nothing prevents it from being correct.

Your approach of wrapping the factory in a class is an organizational change. Organization itself is neither good nor bad. It can be done well or poorly.

You should be fine doing whichever approach feels comfortable for its context. I have also seen both approaches used many times and neither were particularly problematic.

like image 171
Drew Dormann Avatar answered Nov 15 '22 10:11

Drew Dormann