@@ -11,29 +11,17 @@ public class VisitorLambda {
1111 public static class LambdaVisitor <A > implements Function <Object , A > {
1212 private Map <Class <?>, Function <Object , A >> fMap = new HashMap <>();
1313
14- public <B > Acceptor <A , B > on (Class <B > clazz ) {
15- return new Acceptor <>(this , clazz );
14+ @ SuppressWarnings (value = "unchecked" )
15+ public <B > LambdaVisitor <A > addHandler (Class <B > clazz , Function <B , A > handler ) {
16+ fMap .put (clazz , (Function <Object , A >) handler );
17+ return this ;
1618 }
1719
1820 @ Override
1921 public A apply ( Object o ) {
2022 return fMap .get (o .getClass ()).apply ( o );
2123 }
2224
23- static class Acceptor <A , B > {
24- private final LambdaVisitor visitor ;
25- private final Class <B > clazz ;
26-
27- public Acceptor ( LambdaVisitor <A > visitor , Class <B > clazz ) {
28- this .visitor = visitor ;
29- this .clazz = clazz ;
30- }
31-
32- public LambdaVisitor <A > then (Function <B , A > f ) {
33- visitor .fMap .put ( clazz , f );
34- return visitor ;
35- }
36- }
3725 }
3826
3927 public static class Square {
@@ -63,22 +51,22 @@ public Rectangle( double weidht, double height ) {
6351 }
6452
6553 static Function <Object , Double > areaVisitor = new LambdaVisitor <Double >()
66- .on (Square .class ). then ( s -> s .side * s .side )
67- .on (Circle .class ). then ( c -> Math .PI * c .radius * c .radius )
68- .on (Rectangle .class ). then ( r -> r .height * r .weidht );
54+ .addHandler (Square .class , ( Square s ) -> s .side * s .side )
55+ .addHandler (Circle .class , c -> Math .PI * c .radius * c .radius )
56+ .addHandler (Rectangle .class , r -> r .height * r .weidht );
6957
7058 static Function <Object , Double > perimeterVisitor = new LambdaVisitor <Double >()
71- .on (Square .class ). then ( s -> 4 * s .side )
72- .on (Circle .class ). then ( c -> 2 * Math .PI * c .radius )
73- .on (Rectangle .class ). then ( r -> 2 * r .height + 2 * r .weidht );
59+ .addHandler (Square .class , s -> 4 * s .side )
60+ .addHandler (Circle .class , c -> 2 * Math .PI * c .radius )
61+ .addHandler (Rectangle .class , r -> 2 * r .height + 2 * r .weidht );
7462
7563 public static void main ( String [] args ) {
7664 List <Object > figures = Arrays .asList ( new Circle ( 4 ), new Square ( 5 ), new Rectangle ( 6 , 7 ) );
7765
78- double totalArea = figures .stream ().map ( areaVisitor ).reduce ( 0.0 , ( v1 , v2 ) -> v1 + v2 );
66+ double totalArea = figures .stream ().map ( areaVisitor ).reduce ( 0.0 , Double :: sum );
7967 System .out .println ("Total area = " + totalArea );
8068
81- double totalPerimeter = figures .stream ().map ( perimeterVisitor ).reduce ( 0.0 , ( v1 , v2 ) -> v1 + v2 );
69+ double totalPerimeter = figures .stream ().map ( perimeterVisitor ).reduce ( 0.0 , Double :: sum );
8270 System .out .println ("Total perimeter = " + totalPerimeter );
8371 }
8472}
0 commit comments