c#中反射机制比较常见,而c++中没有该机制。使用c++实现反射机制,主要利用了工厂模式进程对象的生产。
ITest.h | 基类 |
Test.h | 继承类 |
helper.h | 帮助类 |
main.cpp | 主函数入口文件 |
//ITest.h
#pragma once
#include <map>
using namespace std;
class ITestFactory;
typedef map<string, ITestFactory*> MapFactory;
static MapFactory g_mapFactory;
class ITest
{
public:
virtual ~ITest() {};
virtual void TestPrint() = 0;
private:
};
class ITestFactory
{
public:
void registerFactory(string clsName, ITestFactory* pFactory)
{
g_mapFactory.insert(make_pair(clsName, pFactory));
}
virtual ITest* intance() = 0;
};
//Test.h
#pragma once
#include "ITest.h"
class Test: public ITest
{
public:
~Test() {};
void TestPrint()
{
printf("im Test\n");
}
private:
};
class TestFactory :public ITestFactory
{
public:
TestFactory()
{
registerFactory("Test", this);
}
~TestFactory() {};
private:
ITest* intance()
{
static ITest *m_pTest=NULL;
if (NULL == m_pTest)
{
m_pTest = (ITest*)new Test;
}
return m_pTest;
}
};
//Helper.h
#pragma once
#include "ITest.h"
ITest* GetClassByName(string clsName)
{
ITestFactory *pFacory;
map<string, ITestFactory*>::iterator iter;
iter = g_mapFactory.find(clsName);
if (iter!= g_mapFactory.end())
{
pFacory = iter->second;
}
else
{
return NULL;
}
return pFacory->intance();
}
//main.cpp
#include "pch.h"
#include <iostream>
#include "Helper.h"
#include "Test.h"
int main()
{
static TestFactory m_testFactory; //通过构造注册工厂
std::cout << "Hello World!\n";
ITest *p = GetClassByName("Test");
p->TestPrint();
}