C++雜談 簡單工廠模式 裝備 反射機制技能
阿新 • • 發佈:2018-12-20
- 反射機制的實現 Reflect.h
#pragma once
#include <string>
#include <map>
#include <iostream>
typedef void* (*register_func)();
class Object
{
private:
Object(){}
public:
static Object* GetInstance()
{
static Object object;
return &object;
}
void* GetInstanceByClassName(const std::string& class_name)
{
std::map<std::string, register_func>::iterator iter = m_register.find(class_name);
if (iter != m_register.end())
{
return iter->second();
}
else
{
std::cout << "The register is null!" << std::endl;
return nullptr;
}
}
void RegisterClass(const std::string& class_name, register_func func)
{
m_register[class_name] = func;
}
private:
std::map<std::string, register_func> m_register;
};
class Register
{
public:
Register(const std::string& class_name, register_func func)
{
Object::GetInstance()-> RegisterClass(class_name, func);
}
};
#define REGISTER_DECLARE(class_name) \
class_name* ObjectCreator##class_name() \
{ \
return new class_name; \
} \
Register g_Register##class_name(#class_name, (register_func)ObjectCreator##class_name);
- 簡單工廠模式 VirlualMoney.h
#pragma once
#include <iostream>
#include <string>
#include "Reflect.h"
class VirlualMoney
{
public:
VirlualMoney(){}
virtual ~VirlualMoney(){}
};
class BTC
:public VirlualMoney
{
public:
BTC(){ std::cout << "I am BTC!" << std::endl; }
~BTC(){}
};
class ETH
:public VirlualMoney
{
public:
ETH(){ std::cout << "I am ETH!" << std::endl; }
~ETH(){}
private:
};
class VirlualMoneyFactory
{
public:
VirlualMoney* CreateVirlualMoneyObject(const std::string& object)
{
return (VirlualMoney*)Object::GetInstance()->GetInstanceByClassName(object);
}
};
- 牛刀小試
#include <iostream>
#include "VirlualMoney.h"
REGISTER_DECLARE(BTC)
REGISTER_DECLARE(ETH)
int main(int argc, char* argv[])
{
VirlualMoneyFactory creatorDemo;
creatorDemo.CreateVirlualMoneyObject("BTC");
creatorDemo.CreateVirlualMoneyObject("ETH");
return 0;
}
Output