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
76 lines (69 loc) · 1.57 KB
/
Copy pathCompiler.java
File metadata and controls
76 lines (69 loc) · 1.57 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// This code uses factory method along with flyweight
// refactor this to use builder pattern along with flyweight
import java.util.Map;
import java.util.HashMap;
abstract class Expr {
public abstract void genCode();
}
class Constant extends Expr {
private int val;
private static Map<Integer, Constant> pool = new HashMap<>();
public Constant(int arg) {
val = arg;
}
public static Expr make(int val) {
if(!pool.containsKey(val)) {
pool.put(val, new Constant(val));
}
return pool.get(val);
}
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 static Expr make(Expr left, Expr right) {
return new Addition(left, right);
}
public void genCode() {
super.genCode();
System.out.println("iadd");
}
}
class Multiplication extends BinaryExpr {
public Multiplication(Expr arg1, Expr arg2) {
super(arg1, arg2);
}
public static Expr make(Expr left, Expr right) {
return new Multiplication(left, right);
}
public void genCode() {
super.genCode();
System.out.println("imul");
}
}
class Compiler {
public static void main(String []args) {
// ((10 * 20) + 30)
Expr expr = Addition.make(
Multiplication.make(
Constant.make(10),
Constant.make(20)),
Constant.make(30));
expr.genCode();
}
}