Skip to content

Instantly share code, notes, and snippets.

@danilomo
Created June 6, 2018 07:01
Show Gist options
  • Save danilomo/ea5355c71d577f80a81ff57e74a991fd to your computer and use it in GitHub Desktop.
Save danilomo/ea5355c71d577f80a81ff57e74a991fd to your computer and use it in GitHub Desktop.
Visitor pattern revisited
/*
* 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