SE450: A Tree: Recall Composite [7/25] |
file:enumeration/Expr.java [source] [doc-public] [doc-private]
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
package enumeration; public interface Expr { void printPostorder(); int evaluate(); } class Const implements Expr { private final int v; public Const(int v) { this.v = v; } public int evaluate() { return v; } public void printPostorder() { System.out.print(v + " "); } } 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 evaluate() { return op.eval(l.evaluate(), r.evaluate()); } public void printPostorder() { l.printPostorder(); r.printPostorder(); System.out.print(op + " "); } }
file:enumeration/Op.java [source] [doc-public] [doc-private]
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
package enumeration; public abstract class Op { private final String name; Op(String name) { this.name = name; } public String toString() { return name; } public abstract int eval(int x, int y); public static final Op ADD = new OpAdd(); public static final Op SUB = new OpSub(); public static final Op MUL = new OpMul(); public static final Op DIV = new OpDiv(); } final class OpAdd extends Op { OpAdd() { super("+"); } public int eval(int x, int y) { return x+y; } } final class OpSub extends Op { OpSub() { super("-"); } public int eval(int x, int y) { return x-y; } } final class OpMul extends Op { OpMul() { super("*"); } public int eval(int x, int y) { return x*y; } } final class OpDiv extends Op { OpDiv() { super("/"); } public int eval(int x, int y) { return x/y; } }