Closures Factory Example - UnquietCode/Closures-for-Java GitHub Wiki
These examples and more are located in the repository under '/src/test/java/unquietcode/stately/closure/'.
public void factory() {
// Closures can return other closures too, of course.
// Here we create a closure that acts as a factory of adders.
Closure1<Closure1<Integer, Integer>, Integer> adderFactory = new AbstractClosure1<Closure1<Integer, Integer>, Integer>() {
public Closure1<Integer, Integer> run(Integer p1) {
Closure1<Integer, Integer> generated = new AbstractClosure1<Integer, Integer>(p1) {
Integer base = a1();
public Integer run(Integer p1) {
return base + p1;
}
};
return generated;
}
};
// get a few adders and try them out
Closure1<Integer, Integer> add10 = adderFactory.run(10);
Closure1<Integer, Integer> add5 = adderFactory.run(5);
Closure1<Integer, Integer> sub1 = adderFactory.run(-1);
int test = 50;
out(add10.run(test)); // 60
out(add5.run(test)); // 55
out(sub1.run(test)); // 49
}
public void untypedFactory() {
// Only the return type needs to be specified, if you're willing to keep track
// of the necessary number of inputs and their types.
Closure<Closure> adderFactory = new AbstractClosure<Closure>() {
public Closure run(Object...args) {
return new AbstractClosure<Integer>(args[0]) {
Integer base = a1(); // this is optional, since a1() can be used directly
public Integer run(Object...args) {
return base + (Integer) args[0]; // we expect one argument
}
};
}
};
// get a few adders and try them out
Closure add10 = adderFactory.run(10);
Closure add5 = adderFactory.run(5);
Closure sub1 = adderFactory.run(-1);
// you are responsible for passing in the correct number and types of arguments
int test = 50;
out(add10.run(test)); // 60
out(add5.run(test)); // 55
out(sub1.run(test)); // 40
}