由于不会写那个很复杂的宏,就用模板类解决
直接上代码
#include <iostream>
#include <functional>
#include <map>
//Factory: Provide the register method SingleT;
//abstract Product: as the Interface of Product
//Product: many
//the Macro of register ProductNew
class ProductInterface{
public:
virtual void show() = 0;
};
class Factory{
private:
Factory(){};
std::map<std::string,std::function<ProductInterface*()> > methodMap;
public:
~Factory(){};
static Factory* getInstance(){
static Factory f;
return &f;
};
void Register(std::string name, std::function<ProductInterface*()> method){
methodMap.insert(std::pair(name,method));
};
ProductInterface* CreatProduct(std::string name){
auto tempMethod = this->methodMap.at(name);
return tempMethod();
};
};
template<typename T>
class RegisterMethod{
public:
RegisterMethod(std::string name, std::function<T*()> method){
auto f = Factory::getInstance();
f->Register(name,[method](){
return method();
});
}
};
class Product1: public ProductInterface{
public:
Product1(){
}
virtual void show() override{
std::cout<<"Product1 show";
}
};
//
class Product2: public ProductInterface{
public:
Product2(){
}
virtual void show() override{
std::cout<<"Product2 show";
}
};
int main() {
RegisterMethod<Product1>* temp = new RegisterMethod<Product1>("Product1",[](){
Product1* p = new Product1();
return p;
});
RegisterMethod<Product2>* temp1 = new RegisterMethod<Product2>("Product2",[](){
Product2* p = new Product2();
return p;
});
auto p1 = Factory::getInstance()->getInstance()->CreatProduct("Product2");
p1->show();
std::cout << "Hello, World!" << std::endl;
return 0;
}