vlad7576

up05-3(abstract factory)

May 17th, 2020
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1. #define _USE_MATH_DEFINES
  2.  
  3. #include <cmath>
  4. #include <string>
  5. #include <sstream>
  6. #include <iostream>
  7. #include <map>
  8. #include <vector>
  9. #include <algorithm>
  10.  
  11. class FigCreator
  12. {
  13. public:
  14.     virtual Figure *create(const std::string &str) = 0;
  15.  
  16.     virtual ~FigCreator() = default;
  17. };
  18.  
  19. class CircleCreator : public FigCreator
  20. {
  21. public:
  22.     Figure *create(const std::string &str) override
  23.     {
  24.         return Circle::make(str);
  25.     }
  26.  
  27. };
  28.  
  29. class RectangleCreator : public FigCreator
  30. {
  31. public:
  32.     Figure *create(const std::string &str) override
  33.     {
  34.         return Rectangle::make(str);
  35.     }
  36. };
  37.  
  38. class SquareCreator : public FigCreator
  39. {
  40. public:
  41.     Figure *create(const std::string &str) override
  42.     {
  43.         return Square::make(str);
  44.     }
  45. };
  46.  
  47.  
  48. class AbstractFactory
  49. {
  50. public:
  51.  
  52.     static AbstractFactory &factory_instance()
  53.     {
  54.         static AbstractFactory s;
  55.         return s;
  56.     }
  57.  
  58.     Figure *create(const std::string &type, const std::string &params)
  59.     {
  60.         return disc[type]->create(params);
  61.     }
  62.  
  63. private:
  64.     std::map<std::string, FigCreator *> disc = {
  65.             {"C", new CircleCreator()},
  66.             {"S", new SquareCreator()},
  67.             {"R", new RectangleCreator()},
  68.     };
  69.  
  70.     AbstractFactory() = default;
  71.  
  72.     ~AbstractFactory()
  73.     {
  74.         for (auto &c:disc) {
  75.             delete c.second;
  76.         }
  77.     }
  78.  
  79.     AbstractFactory(AbstractFactory const &) = delete;
  80.  
  81.     AbstractFactory &operator=(AbstractFactory const &) = delete;
  82. };
  83.  
  84. int main()
  85. {
  86.     std::vector<Figure *> figures;
  87.     std::string tmp;
  88.     while (!std::getline(std::cin, tmp).eof()) {
  89.         std::stringstream s;
  90.         s << tmp;
  91.         std::string type, param1, param2;
  92.         s >> type >> param1 >> param2;
  93.         figures.push_back(AbstractFactory::factory_instance().create(type, param1 + " " + param2));
  94.     }
  95.  
  96.     std::stable_sort(figures.begin(), figures.end(),
  97.             [](Figure *a, Figure *b) { return a->get_square() < b->get_square(); });
  98.  
  99.     for (auto &c:figures) {
  100.         std::cout << c->to_string() << std::endl;
  101.         delete c;
  102.     }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment