01
02
03
04
05
06
07
08
09
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
|
package composite.three;
public class ExprFactory {
private ExprFactory() {}
static public Expr newConst(int v) {
return new Const(v);
}
static public Expr newPlus(Expr l, Expr r) {
return new BinOp(l, new OpAdd(), r);
}
static public Expr newMinus(Expr l, Expr r) {
return new BinOp(l, new OpSub(), r);
}
static public Expr newMult(Expr l, Expr r) {
return new BinOp(l, new OpMul(), r);
}
static public Expr newQuot(Expr l, Expr r) {
return new BinOp(l, new OpDiv(), r);
}
private static final class Const implements Expr {
private final int v;
public Const(int v) {
this.v = v;
}
public int eval() {
return v;
}
public String toString() {
return Integer.toString(v);
}
}
private static final class BinOp implements Expr {
private final Expr l;
private final Expr r;
private final Op op;
public BinOp(Expr l, Op op, Expr r) {
if ((l == null) || (op == null) || (r == null)) {
throw new IllegalArgumentException();
}
this.op = op;
this.l = l;
this.r = r;
}
public int eval() {
return op.run(l.eval(), r.eval());
}
public String toString() {
return l.toString() + " " + r.toString() + " " + op.toString();
}
}
private static interface Op {
public abstract int run(int x, int y);
}
private static final class OpAdd implements Op {
public String toString() { return "+"; }
public int run(int x, int y) { return x+y; }
}
private static final class OpSub implements Op {
public String toString() { return "-"; }
public int run(int x, int y) { return x-y; }
}
private static final class OpMul implements Op {
public String toString() { return "*"; }
public int run(int x, int y) { return x*y; }
}
private static final class OpDiv implements Op {
public String toString() { return "/"; }
public int run(int x, int y) { return x/y; }
}
}
|