参考:
https://blog.csdn.net/jnu_simba/article/details/9318799
原先有静态变量依赖问题,
https://blog.csdn.net/anonymalias/article/details/38473985
参考这个,又做了改进:
https://blog.csdn.net/liulong1567/article/details/45273017
https://www.mimec.org/blog?page=2
classfactory.h文件
#ifndef CLASSFACTORY_H
#define CLASSFACTORY_H
#include <map>
#include <string>
using namespace std;
#include "boardbase.h"
typedef void* (*register_func)();
class Class
{
public:
static void* newInstance(const string& class_name) {
map<string, register_func>::iterator it = constructors().find(class_name);
if (it == constructors().end())
return NULL;
else
return it->second();
}
static void registerClass(const string& class_name, register_func func) {
constructors()[class_name] = func;
}
private:
//避免static初始化顺序问题导致崩溃
static map<string, register_func>& constructors()
{
/* key is class name and value is function to create instance of class */
static map<string, register_func> m_register;
return m_register;
}
};
class ClassFactory
{
public:
static BoardBase* createBoardBase(const string& bank_name) {
return (BoardBase*)Class::newInstance(bank_name);
}
};
class Register
{
public:
Register(const string& class_name, register_func func) {
Class::registerClass(class_name, func);
}
};
//在cpp文件中使用
#define REGISTER_CLASS(class_name)
class class_name##Register {
public:
static void* newInstance() {
return new class_name;
}
private:
static Register reg;
};
Register class_name##Register::reg(#class_name,class_name##Register::newInstance);
#endif // CLASSFACTORY_H