-
Notifications
You must be signed in to change notification settings - Fork 1
/
AcyclicVisitor.java
112 lines (94 loc) · 2.48 KB
/
AcyclicVisitor.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Visitor pattern - acyclic visitor; example will PRINT a tree of expressions (ie: 1 + 2)
package behavioral.visitor.acyclic;
interface Visitor {} // marker interface - empty interface
//interface segregation - each visit() in these interfaces is independent from other visit() methods
interface ExpressionVisitor extends Visitor
{
void visit(Expression obj);
}
interface DoubleExpressionVisitor extends Visitor
{
void visit(DoubleExpression obj);
}
interface AdditionExpressionVisitor extends Visitor
{
void visit(AdditionExpression obj);
}
// Base class
abstract class Expression
{
public void accept(Visitor visitor)
{
if (visitor instanceof ExpressionVisitor)
((ExpressionVisitor)visitor).visit(this);
}
}
class DoubleExpression extends Expression
{
public double value;
public DoubleExpression(double value) {
this.value = value;
}
@Override
public void accept(Visitor visitor)
{
if (visitor instanceof DoubleExpressionVisitor)
((DoubleExpressionVisitor)visitor).visit(this);
}
}
class AdditionExpression extends Expression
{
public Expression left, right;
public AdditionExpression(Expression left, Expression right) {
this.left = left;
this.right = right;
}
@Override
public void accept(Visitor visitor)
{
if (visitor instanceof AdditionExpressionVisitor)
((AdditionExpressionVisitor)visitor).visit(this);
}
}
// Here you get to select which expressions you want to implement
class ExpressionPrinter
implements DoubleExpressionVisitor, AdditionExpressionVisitor
{
private StringBuilder sb = new StringBuilder();
@Override
public void visit(DoubleExpression e)
{
sb.append(e.value);
}
@Override
public void visit(AdditionExpression e)
{
sb.append("(");
e.left.accept(this);
sb.append("+");
e.right.accept(this);
sb.append(")");
}
@Override
public String toString()
{
return sb.toString();
}
}
class AcyclicDemo
{
public static void main(String[] args)
{
// 1 + (2+3) = 6
AdditionExpression e = new AdditionExpression(
new DoubleExpression(1),
new AdditionExpression(
new DoubleExpression(2),
new DoubleExpression(3)
)
);
ExpressionPrinter ep = new ExpressionPrinter();
ep.visit(e);
System.out.println(ep);
}
}