-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreflection2.cpp
More file actions
60 lines (50 loc) Β· 1.58 KB
/
reflection2.cpp
File metadata and controls
60 lines (50 loc) Β· 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef void *(*PTRCreateObject)(void);
class ClassFactory {
private:
map<string, PTRCreateObject> m_classMap;
ClassFactory(){}; //ζι ε½ζ°η§ζε
public:
void *getClassByName(string className);
void registClass(string name, PTRCreateObject method);
static ClassFactory &getInstance();
};
void *ClassFactory::getClassByName(string className) {
map<string, PTRCreateObject>::const_iterator iter;
iter = m_classMap.find(className);
if (iter == m_classMap.end())
return NULL;
else
return iter->second();
}
void ClassFactory::registClass(string name, PTRCreateObject method) {
m_classMap.insert(pair<string, PTRCreateObject>(name, method));
}
ClassFactory &ClassFactory::getInstance() {
static ClassFactory sLo_factory;
return sLo_factory;
}
class RegisterAction {
public:
RegisterAction(string className, PTRCreateObject ptrCreateFn) {
ClassFactory::getInstance().registClass(className, ptrCreateFn);
}
};
#define REGISTER(className) \
className *objectCreator##className() { return new className; } \
RegisterAction g_creatorRegister##className( \
#className, (PTRCreateObject)objectCreator##className)
// test class
class TestClass {
public:
void m_print() { cout << "hello TestClass" << endl; };
};
REGISTER(TestClass);
int main(int argc, char *argv[]) {
TestClass *ptrObj =
(TestClass *)ClassFactory::getInstance().getClassByName("TestClass");
ptrObj->m_print();
}