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
static Foo *make()
or similar inside theFoo
base class. I really don't understand what's going on with the singleton in your second example... – Lease