#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 = m_register.find(class_name);
if (it == m_register.end())
return NULL;
else
return it->second();
}
static void registerClass(const string& class_name, register_func func) {
m_register[class_name] = func;
}
private:
/* key is class name and value is function to create instance of class */
static map<string, register_func> m_register;
};
class ClassFactory
{
public:
static BoardBase* createBoardBase(const string& bank_name) {
return (BoardBase*)Class::newInstance(bank_name);
}
private:
ClassFactory();
};
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 const Register reg; \
};\
const Register class_name##Register::reg(#class_name,class_name##Register::newInstance);
#endif // CLASSFACTORY_H