News for hackers. Stuff that matters.
Re:The visitor pattern is essentially the same thing as Chur... by dfgdghdf on Thursday February 04, 2021 @08:19AM (#26025067)
This might get messy once you need hashCode and equals
Re:The visitor pattern is essentially the same thing as Chur... by _old_dude_ on Thursday February 04, 2021 @09:03AM (#26025371)
You can keep the Circle and Rectangle as class (record here) and only see them as Shape when you want to do the double dispatch of the visitor.

  interface Shape {
    record Circle(int x, int w, int r) {}
    record Rectangle(int x, int y, int w, int h) {}

    <T> T apply(Function<Circle, T> _circle, Function<Rectangle, T> _rectangle);

    static <T> Shape shape(Circle circle) {
      return new Shape() {
        @Override
        public <T> T apply(Function<Circle, T> _circle, Function<Rectangle, T> _rectangle) {
          return _circle.apply(circle);
        }
      };
    }
    static <T> Shape shape(Rectangle rectangle) {
      return new Shape() {
        @Override
        public <T> T apply(Function<Circle, T> _circle, Function<Rectangle, T> _rectangle) {
          return _rectangle.apply(rectangle);
        }
      };
    }

    static double area(Shape shape) {
      return shape.apply(
          circle -> Math.PI * circle.r * circle.r,
          rectangle -> 1. * rectangle.w * rectangle.h
      );
    }

    static void main(String[] args) {
      var aCircle = new Circle(2, 1, 4);
      var aRectangle = new Rectangle(1, 3, 10, 7);

      System.out.println(area(shape(aCircle)));
      System.out.println(area(shape(aRectangle)));
    }
  }