fork download
  1. #include <iostream>
  2. #include <functional>
  3. #include <map>
  4. #include <typeinfo>
  5. #include <memory>
  6. using namespace std;
  7.  
  8. struct IAnimal;
  9. struct AnimalFactory
  10. {
  11. using FactoryFunction = std::function<IAnimal*(std::string)>;
  12. bool RegisterFunction(std::string name, FactoryFunction f)
  13. {
  14. factoryMap.insert(std::make_pair(name,f));
  15. return true;
  16. }
  17. std::unique_ptr<IAnimal> CreateAnimal(std::string name, std::string xml)
  18. {
  19. return std::unique_ptr<IAnimal>(factoryMap.at(name)(xml));
  20. }
  21. static AnimalFactory &instance()
  22. {
  23. static AnimalFactory factory{};
  24. return factory;
  25. }
  26.  
  27. private:
  28. std::map<std::string, FactoryFunction> factoryMap;
  29.  
  30. };
  31.  
  32. struct IAnimal{virtual ~IAnimal(){}};
  33.  
  34. struct Cat : IAnimal
  35. {
  36. Cat (std::string xml) {}
  37. static Cat* CreateAnimal(std::string xml) { return new Cat(xml); }
  38. static bool registered;
  39. };
  40. bool Cat::registered = AnimalFactory::instance().RegisterFunction("cat", Cat::CreateAnimal);
  41.  
  42. struct Elephant : IAnimal
  43. {
  44. Elephant (std::string xml) {}
  45. static Elephant* CreateAnimal(std::string xml) { return new Elephant(xml); }
  46. static bool registered;
  47. };
  48. bool Elephant::registered = AnimalFactory::instance().RegisterFunction("elephant", Elephant::CreateAnimal);
  49.  
  50.  
  51.  
  52. int main()
  53. {
  54. auto cat = AnimalFactory::instance().CreateAnimal("cat","hi");
  55. auto elephant = AnimalFactory::instance().CreateAnimal("elephant","hi");
  56.  
  57. std::cout << typeid(*cat).name() << std::endl;
  58. std::cout << typeid(*elephant).name() << std::endl;
  59. }
  60.  
Success #stdin #stdout 0s 3280KB
stdin
Standard input is empty
stdout
3Cat
8Elephant