fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. struct Visitor;
  5.  
  6. struct Shape {
  7. virtual void accept(std::unique_ptr<Visitor> v) = 0;
  8. };
  9.  
  10. struct Circle : Shape { void accept(std::unique_ptr<Visitor> v) override; };
  11. struct Triangle : Shape { void accept(std::unique_ptr<Visitor> v) override; };
  12. struct Square : Shape { void accept(std::unique_ptr<Visitor> v) override; };
  13.  
  14. struct Point {
  15. Point(float x, float y) {}
  16. };
  17.  
  18. struct Visitor {
  19. virtual void visit(Circle &c) const = 0;
  20. virtual void visit(Triangle &t) const = 0;
  21. virtual void visit(Square &s) const = 0;
  22. };
  23.  
  24.  
  25. void Circle::accept(std::unique_ptr<Visitor> v) {
  26. v->visit(*this);
  27. }
  28. void Triangle::accept(std::unique_ptr<Visitor> v) {
  29. v->visit(*this);
  30. }
  31. void Square::accept(std::unique_ptr<Visitor> v) {
  32. v->visit(*this);
  33. }
  34.  
  35.  
  36. struct SnapToPoint : Visitor {
  37. SnapToPoint(float x, float y) : _point(x, y) {}
  38.  
  39. void visit(Circle &c) const override { std::cout << "Snapped a Circle\n"; }
  40. void visit(Triangle &t) const override { std::cout << "Snapped a Triangle\n"; }
  41. void visit(Square &s) const override { std::cout << "Snapped a Square\n"; }
  42.  
  43. private:
  44. Point _point;
  45. };
  46.  
  47. struct ShapeOperationFactory {
  48. virtual std::unique_ptr<Visitor> snapToPoint(float x, float y) const = 0;
  49. };
  50.  
  51. struct MyShapeOpFactory : ShapeOperationFactory {
  52. std::unique_ptr<Visitor> snapToPoint(float x, float y) const override {
  53. return std::unique_ptr<Visitor>(new SnapToPoint(x, y));
  54. }
  55. };
  56.  
  57. int main() {
  58.  
  59. Shape *pShape = new Circle;
  60. ShapeOperationFactory *pFactory = new MyShapeOpFactory;
  61.  
  62. pShape->accept(pFactory->snapToPoint(4.0f, 7.0f));
  63.  
  64. delete pFactory;
  65. delete pShape;
  66. return 0;
  67. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
Snapped a Circle