You are here

Factory with Anonymous Inner Classes

6 June, 2016 - 15:17
Available under Creative Commons-ShareAlike 4.0 International License. Download for free at http://cnx.org/contents/402b20ad-c01f-45f1-9743-05eadb1f710e@37.6
 

Comments

package listFW.factory;
import listFW.*;
public class InnerCompListFact implements IListFactory {
public static final InnerCompListFact Singleton = new InnerCompListFact();
private InnerCompListFact() {
}
 
 
private final static IListAlgo ToStrHelp = new IListAlgo() {
public Object emptyCase(IMTList host, Object... acc) {
return acc[0] + ")";
}
public Object nonEmptyCase(INEList host, Object... acc) {
return host.getRest().execute(this, acc[0] + ", " + host.getFirst());
}
}; // PAY ATTENTION TO THE SEMI-COLON HERE!
 
 
private final static IMTList MTSingleton = new IMTList (){
public Object execute(IListAlgo algo, Object... inp) {
return algo.emptyCase(this, inp);
}
public String toString() {
return "()";
}
}; // PAY ATTENTION TO THE SEMI-COLON HERE!
 
 
public IMTList makeEmptyList() {
return MTSingleton;
}
 
 
public INEList makeNEList(final Object first, final IList rest) {
return new INEList() {
public Object getFirst() {
return first;
}
public IList getRest() {
return rest;
}
public Object execute(IListAlgo algo, Object... inp) {
return algo.nonEmptyCase(this, inp);
}
public String toString() {
return (String)rest.execute(ToStrHelp, "(" + first);
}
};
}
}
 

Note how the code inside the anonymous inner class references first and rest of the parameter list. first and rest are said to be in the closure of the anonymous inner class. Here is an important Java syntax rule: For an local inner class defined inside of a method to access a local variable of the method, this local variable must be declared as final.