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
46 lines (42 loc) · 1.06 KB
/
Copy pathCompiler.java
File metadata and controls
46 lines (42 loc) · 1.06 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
// This code works, but follows procedural approach
// Task: Convert it to Object Oriented approach and apply Composite pattern
class Expr {
Expr left;
String value;
Expr right;
public Expr(Expr left, String value, Expr right) {
this.left = left;
this.value = value;
this.right = right;
}
void genCode() {
if(this == null)
return;
if((left == null) && (right == null)) {
System.out.println("iload " + value);
}
else { // its an intermediate node
left.genCode();
right.genCode();
switch(value) {
case "+": System.out.println("iadd"); break;
case "-": System.out.println("isub"); break;
case "*": System.out.println("imul"); break;
case "/": System.out.println("idiv"); break;
default:
System.out.println("Not implemented yet!");
}
}
}
}
class Compiler {
public static void main(String []args) {
// ((10 * 20) + 30)
Expr expr = new Expr(
new Expr(
new Expr(null, "10", null), "*", new Expr(null, "20", null)),
"+",
new Expr(null, "30", null));
expr.genCode();
}
}