C++ 工厂+反射+配置文件

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

typedef void* (*register_func)();

class CReflect
{
public:
	static void* newInstance(const string& class_name) 
	{
		std::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 std::map<string, register_func> m_register;
};


class Register
{
public:
    Register(const string& class_name, register_func func)
	{
        CReflect::registerClass(class_name, func);
    }
};

#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);

#pragma once
#include <iostream>
using namespace std;


class testA
{
public:
	testA(void);
	~testA(void);

public:
	void Show(){ std::cout << "Hello reflect" << std::endl;}
};

#pragma once
#include "testA.h"
#include "Reflect.h"



class testB
{
public:
	static testA * GetInstance(const std::string& strDevName)
	{
		if(strDevName.empty())
		{
			return NULL;
		}

		return (testA*)CReflect::newInstance(strDevName);
	}
};

// reflect_test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "testA.h"
#include "testB.h"

int _tmain(int argc, _TCHAR* argv[])
{
	testA *lp = testB::GetInstance("testA");
	lp->Show();
	return 0;
}



1.创建反射
2.创建工厂
3.创建需要创建的类
4.通过工厂获取相应的类指针


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值