-
Notifications
You must be signed in to change notification settings - Fork 1
/
VisitorCodingExercise.java
127 lines (107 loc) · 2.69 KB
/
VisitorCodingExercise.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
Exercise for visitor section:
You are asked to implement a double-dispatch visitor called ExpressionPrinter for printing different mathematical
expressions. The range of expressions covers addition and multiplication - please put round brackets after
around addition but not around multiplication! Also, please avoid any blank spaces in output. Example:
• Input:AdditionExpression(Value(2), Value(3))
• Output:(2+3)
*/
package behavioral.visitor.exercise;
abstract class ExpressionVisitor
{
abstract void visit(Value value);
abstract void visit(AdditionExpression ae);
abstract void visit(MultiplicationExpression me);
}
abstract class Expression
{
abstract void accept(ExpressionVisitor ev);
}
class Value extends Expression
{
public int value;
public Value(int value)
{
this.value = value;
}
@Override
void accept(ExpressionVisitor ev)
{
ev.visit(this);
}
}
class AdditionExpression extends Expression
{
public Expression lhs, rhs;
public AdditionExpression(Expression lhs, Expression rhs)
{
this.lhs = lhs;
this.rhs = rhs;
}
@Override
void accept(ExpressionVisitor ev)
{
ev.visit(this);
}
}
class MultiplicationExpression extends Expression
{
public Expression lhs, rhs;
public MultiplicationExpression(Expression lhs, Expression rhs)
{
this.lhs = lhs;
this.rhs = rhs;
}
@Override
void accept(ExpressionVisitor ev)
{
ev.visit(this);
}
}
class ExpressionPrinter extends ExpressionVisitor
{
private StringBuilder sb = new StringBuilder();
@Override
void visit(Value value)
{
sb.append(value.value);
}
@Override
void visit(AdditionExpression ae)
{
sb.append("(");
ae.lhs.accept(this);
sb.append("+");
ae.rhs.accept(this);
sb.append(")");
}
@Override
void visit(MultiplicationExpression me)
{
me.lhs.accept(this);
sb.append("*");
me.rhs.accept(this);
}
@Override
public String toString()
{
return sb.toString();
}
}
class VisitorExerciseDemo
{
public static void main(String[] args)
{
AdditionExpression simple = new AdditionExpression(new Value(2), new Value(3));
ExpressionPrinter ep = new ExpressionPrinter();
ep.visit(simple);
System.out.println(ep); // (2+3)
MultiplicationExpression expr = new MultiplicationExpression(
new AdditionExpression(new Value(2), new Value(3)),
new Value(4)
);
ExpressionPrinter ep2 = new ExpressionPrinter();
ep2.visit(expr);
System.out.println(ep2); // (2+3)*4
}
}