Created
June 6, 2018 07:00
-
-
Save danilomo/31f58d2fd08a0906e989b185e818c1b8 to your computer and use it in GitHub Desktop.
Visitor pattern example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package visitorchallenge; | |
import ast.Exp; | |
import ast.MulExp; | |
import ast.NegExp; | |
import ast.NumberLiteral; | |
import ast.SumExp; | |
import ast.Visitor; | |
/** | |
* | |
* @author danilo | |
*/ | |
public class VisitorOld { | |
public static void main(String[] args) { | |
Visitor<None> v = new Visitor<None>() { | |
@Override | |
public None visit(NumberLiteral nl) { | |
print(nl.value()); | |
return NONE; | |
} | |
@Override | |
public None visit(NegExp nl) { | |
print("(- "); | |
nl.exp().accept(this); | |
print(")"); | |
return NONE; | |
} | |
@Override | |
public None visit(MulExp nl) { | |
print("(* "); | |
nl.left().accept(this); | |
print(" "); | |
nl.right().accept(this); | |
print(")"); | |
return NONE; | |
} | |
@Override | |
public None visit(SumExp nl) { | |
print("(+ "); | |
nl.left().accept(this); | |
print(" "); | |
nl.right().accept(this); | |
print(")"); | |
return NONE; | |
} | |
}; | |
Exp exp = new SumExp(new SumExp(new NumberLiteral(1.0), new NegExp(new NumberLiteral(10))), new MulExp(new NumberLiteral(10.0), new NumberLiteral(20))); | |
exp.accept(v); | |
} | |
private static None NONE = new None(); | |
private static void print(Object o) { | |
System.out.print(o); | |
} | |
static class None { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment