Factory patternGeneric Factory in C++
A generic factory is a factory that can register any class type. It is very easy to write because we are allowed to use void pointers.
#include <functional>
class Factory
{
public:
Factory() {}
~Factory() {}
void Register(const std::string _key, const std::function<void *()> _creator)
{
m_creators[_key] = _creator;
}
template<typename ClassType>
ClassType* Get(const std::string _key) const
{
return static_cast<ClassType *>(m_creators.at(_key)());
}
private:
std::map<std::string, std::function<void *()> > m_creators;
};
Usage:
int main()
{
Factory f;
f.Register("Derived1", &BaseClass<Derived1>::CreateInterface);
f.Register("Derived2", &BaseClass<Derived2>::CreateInterface);
Derived1 *d1 = f.Get<Derived1>("Derived1");
Derived2 *d2 = f.Get<Derived2>("Derived2");
Derived1 *d2 = f.Get<Derived1>("Derived2"); // This also compiles!!!
}
As we are simply casting a void pointer, it is left to the developer to ensure the right class type is passed to Factory::Get function, which might not be the best practice.


