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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With