C++仿Java反射机中字符串创建类的思想,初步实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq78442761/article/details/88034560

目录

 

 

理论

实例


 

理论

因为上午对Java反射机制有了跟进一步认识,这里用C++模仿下,他的思想,并且简单实现了下,这里只是模仿他的思想!

这个思想为:

如果有一个class A,可以使用new A()来创建对象,但如果要使用字符串"A"来创建class A的对象,在Java中通过java.lang.class中的Class可以把一个类当成一个变量,然后通过字符串,去创建,就是反射。

用字符串去创建类!!这个思想!

下面的实例逻辑为:

1) 使用函数指针,指向某一类的创建;

2) 使用map,key为类名,value为调用创建的指针;

3)  在调用前,要实现字符串与函数指针放到map中去。

这个思想结合单例+设计模式感觉将会强大无比,在以后的日子中将会给出!

实例

程序运行截图如下:

程序结构如下:

源码如下:

ClassFactory.h

#ifndef _CLASSFACTORY_
#define _CLASSFACTORY_

#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef void* (*createFun)();
typedef pair<string, createFun> in_pair;

class ClassFactory{

public:
	~ClassFactory(){};

	void registClass(string name, createFun fun);
	static ClassFactory *getInstance();

	void *getClassByName(string name);
	map<string, createFun> &getMap();


private:
	ClassFactory(){};
	map<string, createFun> m_map;
	static ClassFactory *m_classFactory;
};


#endif	//_CLASSFACTORY_

Test.h

#ifndef _TEST_
#define _TEST_

class Test
{
public:
	Test();
	void print();
	~Test();
};

#endif

ClassFactory.cpp

#include "ClassFactory.h"

ClassFactory *ClassFactory::m_classFactory = NULL;

void ClassFactory::registClass(string name, createFun fun){
		
	getInstance()->getMap().insert(in_pair(name, fun));
}

map<string, createFun> &ClassFactory::getMap(){

	return m_map;
}

void *ClassFactory::getClassByName(string name){

	int a = getInstance()->getMap().size();;
	map<string, createFun>::iterator it = getInstance()->getMap().find(name);
	if(it == m_map.end())
		return NULL;

	createFun fun = it->second;
	if(!fun)
		return NULL;

	return fun();
}

ClassFactory *ClassFactory::getInstance(){

	if(m_classFactory == NULL){
		
		m_classFactory = new ClassFactory();
		return m_classFactory;
	}

	return m_classFactory;
}

main.cpp

#include "ClassFactory.h"
#include "Test.h"

void* createTest(){

	Test *t = new Test;
	return t;
}


int main(int argc, char *argv[]){

	ClassFactory::getInstance()->registClass("Test", createTest);

	Test *t = (Test*)ClassFactory::getInstance()->getClassByName("Test");

	if(!t){
		
		cout << "no instance" << endl;
		return -1;
	}

	t->print();
	delete t;
	delete ClassFactory::getInstance();

	getchar();
	return 0;
}

Test.cpp

#include "Test.h"
#include <iostream>
using namespace std;


Test::Test()
{
	cout << "Test Construction called" << endl;
}

void Test::print(){

	cout << "I am print" << endl;
}


Test::~Test()
{
}

猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/88034560
今日推荐