package lrs.visitor; import lrs.*; /** * Reverses the host using local anonymous inner class as a helper visitor. * Creates the helper object each time it is called. * @author DXN */ public class RevLocalInner implements IAlgo { public static final RevLocalInner Singleton = new RevLocalInner (); private RevLocalInner () { } /** * Does nothing: the empty host is the reverse of itself. * @return null */ public Object forEmpty(LRStruct host, Object input) { return null; } /** * Asks for help to recursively move down the host, removes one element at * a time and inserting it to the front of the host. In the end, the host * is reversed. * @return null */ public Object forNonEmpty(final LRStruct host, Object input) { return host.getRest().execute(new IAlgo (){ /** * Does nothing because the end of the original host is reached. * From host to h is the reverse of the original list. * @param h the remaining tail of the list to be reversed. * @param inp not used. * @return null. */ public Object forEmpty(LRStruct h, Object inp) { return null; } /** * Removes the current list's first and insert it to the front of * the original host and recurs. * @param h the remaining tail of the list to be reversed. * @param inp not used. * @return null. */ public Object forNonEmpty(LRStruct h, Object inp) { Object hFirst = h.removeFront(); // h has "advanced". host.insertFront (hFirst); return h.execute(this, null); } }, null); } public static void main (String[] args) { LRStruct p = new LRStruct (); testVisitor (p, RevLocalInner.Singleton, null); p.insertFront(new Integer (-1)); testVisitor (p, RevLocalInner.Singleton, null); p.insertFront (new Integer (3)); testVisitor (p, RevLocalInner.Singleton, null); p.insertFront(new Integer (5)); testVisitor (p, RevLocalInner.Singleton, null); p.insertFront(new Integer (99)); testVisitor (p, RevLocalInner.Singleton, null); } private static void testVisitor(LRStruct p, IAlgo algo, Object input) { // NOTE the use of Object.getClass ()!!! // Also watch what happens when input == null!!! try { System.out.println (p + " execute " + algo.getClass () + ", " + input + "..."); System.out.println (" ---> " + p.execute (algo, input) + " " + p); } catch (Exception e) { System.out.println (e); } } }