-
Notifications
You must be signed in to change notification settings - Fork 1
/
IntrusiveVisitor.java
62 lines (52 loc) · 1.3 KB
/
IntrusiveVisitor.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
// Visitor pattern - intrusive visitor; example will PRINT a tree of expressions (ie: 1 + 2)
package behavioral.visitor.intrusive;
abstract class Expression
{
public abstract void print(StringBuilder sb); // visitor here
}
class DoubleExpression extends Expression
{
private double value;
public DoubleExpression(double value) {
this.value = value;
}
// Visitor is here.
@Override
public void print(StringBuilder sb)
{
sb.append(value);
}
}
class AdditionExpression extends Expression
{
private Expression left, right;
public AdditionExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public void print(StringBuilder sb) {
sb.append("(");
left.print(sb);
sb.append("+");
right.print(sb);
sb.append(")");
}
}
class IntrusiveDemo
{
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();
e.print(sb);
System.out.println(sb);
}
}