forked from CodeOpsTech/DesignPatternsJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompiler.java
More file actions
59 lines (53 loc) · 1.09 KB
/
Copy pathCompiler.java
File metadata and controls
59 lines (53 loc) · 1.09 KB
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
// refactor this code to use factory method instead of constructors for the nodes
abstract class Expr {
public abstract void genCode();
}
class Constant extends Expr {
int val;
public Constant(int arg) {
val = arg;
}
public void genCode() {
System.out.println("iload " + val);
}
}
class BinaryExpr extends Expr {
private Expr left, right;
public BinaryExpr(Expr arg1, Expr arg2) {
left = arg1;
right = arg2;
}
public void genCode() {
left.genCode();
right.genCode();
}
}
class Addition extends BinaryExpr {
public Addition(Expr arg1, Expr arg2) {
super(arg1, arg2);
}
public void genCode() {
super.genCode();
System.out.println("iadd");
}
}
class Multiplication extends BinaryExpr {
public Multiplication(Expr arg1, Expr arg2) {
super(arg1, arg2);
}
public void genCode() {
super.genCode();
System.out.println("imul");
}
}
class Compiler {
public static void main(String []args) {
// ((10 * 20) + 30)
Expr expr = new Addition(
new Multiplication(
new Constant(10),
new Constant(20)),
new Constant(30));
expr.genCode();
}
}