-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReflectiveVisitor.java
67 lines (56 loc) · 1.52 KB
/
ReflectiveVisitor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Visitor pattern - reflective visitor; example will PRINT a tree of expressions (ie: 1 + 2)
package behavioral.visitor.reflective;
abstract class Expression
{
}
class DoubleExpression extends Expression
{
public double value;
public DoubleExpression(double value) {
this.value = value;
}
}
class AdditionExpression extends Expression
{
public Expression left, right;
public AdditionExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
}
class ExpressionPrinter
{
public static void print(Expression e, StringBuilder sb)
{
// Main issue is that code is slow due to checking type
if (e.getClass() == DoubleExpression.class)
{
sb.append(((DoubleExpression)e).value);
} else if(e.getClass() == AdditionExpression.class)
{
AdditionExpression ae = (AdditionExpression) e;
sb.append("(");
print(ae.left, sb);
sb.append("+");
print(ae.right, sb);
sb.append(")");
}
}
}
class ReflectiveDemo
{
public static void main(String[] args)
{
// 1 + (2+3)
AdditionExpression e = new AdditionExpression(
new DoubleExpression(1),
new AdditionExpression(
new DoubleExpression(2),
new DoubleExpression(3)
)
);
StringBuilder sb = new StringBuilder();
ExpressionPrinter.print(e, sb);
System.out.println(sb);
}
}