一个通过宏在工厂类中注册产品类的实现例子
#include <functional> #include <iostream> #include <memory> #include <unordered_map> class AbstractModule { public: virtual void show() = 0; }; class ConcreteModule1 : public AbstractModule { public: void show() override { std::cout << "In ConcreteModule1 show()." << std::endl; } static std::shared_ptr<AbstractModule> create() { std::cout << "In ConcreteModule1 create()." << std::endl; return std::make_shared<ConcreteModule1>(); } }; class ConcreteModule2 : public AbstractModule { public: void show() override { std::cout << "In ConcreteModule2 show()." << std::endl; } static std::shared_ptr<AbstractModule> create() { std::cout << "In ConcreteModule2 create()." << std::endl; return std::make_shared<ConcreteModule2>(); } }; static std::unordered_map<std::string, std::function<std::shared_ptr<AbstractModule>()>> m; class Factory { public: static void registorModule(std::string modulename, std::function<std::shared_ptr<AbstractModule>()> f) { m.insert(std::make_pair(modulename, f)); } static std::shared_ptr<AbstractModule> getModule(std::string modulename) { if (m.count(modulename)) { return (m.at(modulename))(); } return nullptr; } }; #define REGISTOR(classname) \ Factory::registorModule(#classname, classname::create); int main(int argc, char *argv[]) { REGISTOR(ConcreteModule1); REGISTOR(ConcreteModule2); std::shared_ptr<AbstractModule> cm1 = Factory::getModule("ConcreteModule1"); if (cm1) { cm1->show(); } std::shared_ptr<AbstractModule> cm2 = Factory::getModule("ConcreteModule2"); if (cm2) { cm2->show(); } std::shared_ptr<AbstractModule> cm3 = Factory::getModule("ConcreteModule3"); if (cm3) { cm3->show(); } return 1; }