package lrs.visitor; import lrs.*; /** * Reverses the host using anonymous class as a helper visitor. Creates the * helper object once. Avoids having to name the helper. * @author DXN */ public class ReverseAnonymous implements IAlgo { public static final ReverseAnonymous Singleton = new ReverseAnonymous (); /** * Helper visitor as an anonymous class. This is not an inner class. */ private static final IAlgo reverseHelp= new IAlgo () { /** * Does nothing because the host is empty. * From top to host is the reverse of the original list. * @param host the remaining tail of the list to be reversed. * @param top from top to host is the reversed list so far. * @return null. */ public Object forEmpty(LRStruct host, Object top) { return null; } /** * Removes the host's first and insert it to the front of the top, and * recurs. * @param host the remaining tail of the list to be reversed. * @param top from top to host is the reversed list so far. * @return null. */ public Object forNonEmpty(LRStruct host, Object top) { Object hostFirst = host.removeFront(); // host has "advanced". ((LRStruct)top).insertFront (hostFirst); return host.execute(this, top); } }; private ReverseAnonymous () { } /** * 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(LRStruct host, Object input) { return host.getRest().execute(reverseHelp, host); } }