2 ms·
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 Sha
by _old_dude_ 6y ago
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)));
}
}