api.h
#pragma once
#include<string>
#include<iostream>
class API {
public:
virtual void run(std::string) = 0;
protected:
API() {};
};
class BAPI : public API {
public:
virtual void run(std::string str)override {
std::cout << "BAPI:" << str << std::endl;
}
};
class PAPI : public API {
public:
virtual void run(std::string str) override {
std::cout << "PAPI:" << str << std::endl;
}
};
class Factory {
inline static API* createAPI(int type) {
if (type == 0)return new BAPI();
if (type == 1)return new PAPI();
}
};
Dyobj.h
#pragma once
#ifndef DYNOBJ
#define DYNOBJ
#include<string>
#include<map>
#include "API.h"
typedef void* (*Constructor)();
class CObjectFactor {
public:
static void registerClass(std::string className, Constructor constructor) {
constructors()[className] = constructor;
}
static void* createObject(std::string className) {
Constructor constructor = nullptr;
if (constructors().find(className)!= constructors().end())
{
constructor = constructors().find(className)->second;
}
if (constructor == NULL)
{
return NULL;
}
return constructor();
}
private:
inline static std::map<std::string, Constructor>& constructors() {
static std::map<std::string, Constructor> instance;
return instance;
}
};
/*
class ImplHelper {
public:
ImplHelper() {
CObjectFactor::registerClass("BAPI", ImplHelper::createObjFunc);
}
static void* createObjFunc() {
return new BAPI();
}
};
*/
#define REGISTER_CLASS(className)\
class className##ImplHelper {\
public:\
className##ImplHelper() {\
CObjectFactor::registerClass(#className, className##ImplHelper::createObjFunc);\
}\
static void* createObjFunc() {\
return new className();\
}\
};\
className##ImplHelper className##Helper;
#endif // !DYNOBJ
main.cpp
#include<iostream>
#include<string>
#include "DynObj.h"
#include "API.h"
REGISTER_CLASS(PAPI);
REGISTER_CLASS(BAPI);
int main(int argc, char** argv) {
BAPI* p1 = static_cast<BAPI*>(CObjectFactor::createObject("BAPI"));
PAPI* p2 = static_cast<PAPI*>(CObjectFactor::createObject("PAPI"));
p1->run("dddddd");
p2->run("dddd");
delete p1;
delete p2;
return 0;
}
标签:std,设计模式,void,工厂,className,static,简单,ImplHelper,include
From: https://www.cnblogs.com/xcodingfork/p/17134700.html