// class_factory.h
#include <map>
#include <string>
#include <functional>
#include <memory>
template <typename classType>
class ClassFactory
{
private:
ClassFactory(){}
std::map<std::string, std::function<std::shared_ptr<classType>()>> _obj_func_container;
public:
// get class by name
std::shared_ptr<classType>
get_class_by_name(std::string class_name)
{
auto it = _obj_func_container.find(class_name);
if (it == _obj_func_container.end())
return nullptr;
std::function<std::shared_ptr<classType>()> obj_func = it->second;
return obj_func();
}
// regist
void regist_class(std::string class_name, std::function<std::shared_ptr<classType>()> obj_func)
{
_obj_func_container[class_name] = obj_func;
}
// get sigleton
static ClassFactory& get_instance()
{
static ClassFactory<classType> cf;
return cf;
}
};
// TestClass.h
#include <iostream>
#include <memory>
class TestClass
{
public:
TestClass()
{
std::cout<<"TestClass()"<<std::endl;
}
~TestClass()
{
std::cout<<"~TestClass()"<<std::endl;
}
void print_func()
{
std::cout<<"TestClass::print_func"<<std::endl;
}
};
std::shared_ptr<TestClass> creat_testclass()
{
return std::make_shared<TestClass>();
}
// main.cpp
#include <iostream>
#include "class_factory.h"
#include "TestClass.h"
using namespace std;
int main()
{
ClassFactory<TestClass>& cf = ClassFactory<TestClass>::get_instance();
cf.regist_class("TestClass", creat_testclass);
std::shared_ptr<TestClass> t = cf.get_class_by_name("TestClass");
t->print_func();
return 0;
}
运行截图