Created
June 6, 2018 07:01
-
-
Save danilomo/ea5355c71d577f80a81ff57e74a991fd to your computer and use it in GitHub Desktop.
Visitor pattern revisited
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 java.util.HashMap; | |
import java.util.Map; | |
/** | |
* | |
* @author danilo | |
*/ | |
public class VisitorAlternative { | |
static Map<Class, Funct<? extends Exp, Void>> map; | |
static { | |
map = new HashMap<>(); | |
map.put(SumExp.class, (SumExp e) -> { | |
System.out.println("SumExp."); | |
return null; //To change body of generated lambdas, choose Tools | Templates. | |
}); | |
map.put(MulExp.class, (MulExp e) -> { | |
System.out.println("MulExp ."); | |
return null; //To change body of generated lambdas, choose Tools | Templates. | |
}); | |
} | |
static <T extends Exp> void apply(T t) { | |
Funct<T, Void> f = (Funct<T, Void>) map.get(t.getClass()); | |
f.apply(t); | |
} | |
public static void main(String[] args) { | |
final SumExp exp = new SumExp( | |
new SumExp( | |
new NumberLiteral(1.0), | |
new NegExp(new NumberLiteral(10))), | |
new MulExp( | |
new NumberLiteral(10.0), | |
new NumberLiteral(20))); | |
Exp exp1 = exp.left(); | |
Exp exp2 = exp.right(); | |
apply(exp1); | |
apply(exp2); | |
} | |
interface Funct<T, V> { | |
V apply(T t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment