jack06215

[tutorial] Factory pattern

Jul 17th, 2020 (edited)
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <functional>
  4. #include <vector>
  5.  
  6. // Base class
  7. class Shape
  8. {
  9.   public:
  10.     virtual void draw() = 0;
  11. };
  12.  
  13. // Factory class
  14. class ShapeFactory
  15. {
  16.   public:
  17.     typedef std::unordered_map<std::string, std::function<Shape*()>> registry_map;
  18.  
  19.     // use this to instantiate the proper Derived class
  20.     static Shape * instantiate(const std::string& name)
  21.     {
  22.       auto it = ShapeFactory::registry().find(name);
  23.       return it == ShapeFactory::registry().end() ? nullptr : (it->second)();
  24.     }
  25.  
  26.     static registry_map & registry()
  27.     {
  28.       static registry_map impl;
  29.       return impl;
  30.     }
  31.  
  32. };
  33.  
  34. template<typename T> struct ShapeFactoryRegister
  35. {
  36.     ShapeFactoryRegister(std::string name)
  37.     {
  38.       ShapeFactory::registry()[name] = []() { return new T; };
  39.       std::cout << "Registering class '" << name << "'\n";
  40.     }
  41. };
  42.  
  43.  
  44. class Circle : public Shape
  45. {
  46.   public:
  47.     void draw() {  std::cout << "drawing a circle " <<std::endl;  }
  48.   private:
  49.     static ShapeFactoryRegister<Circle> AddToFactory_;
  50. };
  51.  
  52. ShapeFactoryRegister<Circle> Circle::AddToFactory_("Circle" );
  53.  
  54. //------------------
  55.  
  56. class Square : public Shape
  57. {
  58.   public:
  59.     void draw() {  std::cout << "drawing a square " <<std::endl;  }
  60.   private:
  61.     static ShapeFactoryRegister<Square> AddToFactory_;
  62. };
  63.  
  64. ShapeFactoryRegister<Square> Square::AddToFactory_("Square" );
  65.  
  66.  
  67.  
  68. class Ellipse : public Shape
  69. {
  70.   public:
  71.     void draw() {  std::cout << "drawing an ellipse " <<std::endl;  }
  72.   private:
  73.     static ShapeFactoryRegister<Ellipse> AddToFactory_;
  74. };
  75.  
  76. ShapeFactoryRegister<Ellipse> Ellipse::AddToFactory_("Ellipse" );
  77.  
  78.  
  79.  
  80.  
  81. int main(int argc, char *argv[])
  82. {
  83.   std::vector<Shape*> shapes;
  84.  
  85.   shapes.push_back( ShapeFactory::instantiate("Circle") );
  86.   shapes.push_back( ShapeFactory::instantiate("Square") );
  87.   shapes.push_back( ShapeFactory::instantiate("Ellipse") );
  88.  
  89.   for (auto& shape: shapes){
  90.     shape->draw();
  91.   }
  92.   return 0;
  93. }
Add Comment
Please, Sign In to add comment