001 package listFW.visitor; 002 import listFW.*; 003 004 /** 005 * Computes a String reprsentation of IList showing a left parenthesis followed 006 * by elements of the IList separated by commas, ending with with a right parenthesis. 007 * This code has been written to make it run on any list. 008 * @stereotype visitor 009 * @author D.X. Nguyen, S. Wong 010 * @since 07/01/2004 011 * @author Mathias Ricken - Copyright 2008 - All rights reserved. 012 */ 013 public class ToStringAlgo implements IListAlgo<Object, String, Object> { 014 015 public static final ToStringAlgo Singleton = new ToStringAlgo(); 016 private ToStringAlgo() { 017 } 018 019 /** 020 * Returns "()". 021 */ 022 public String emptyCase(IMTList<? extends Object> host, Object ... inp) { 023 return "()"; 024 } 025 026 /** 027 * Passes "(" + first to the rest of IList and asks for help to complete the computation. 028 */ 029 public String nonEmptyCase(INEList<? extends Object> host, Object ... inp) { 030 return host.getRest().execute(ToStringHelper.Singleton, "(" + host.getFirst()); 031 } 032 } 033 034 /** 035 * Helps ToStringAlgo compute the String representation of the rest of the list. 036 */ 037 class ToStringHelper implements IListAlgo<Object, String, String> { 038 public static final ToStringHelper Singleton = new ToStringHelper(); 039 private ToStringHelper() { 040 } 041 042 /** 043 * Returns the accumulated String + ")". 044 * At end of list: done! 045 */ 046 public String emptyCase(IMTList<? extends Object> host, String ... acc) { 047 return acc[0] + ")"; 048 } 049 050 /** 051 * Continues accumulating the String representation by appending ", " + first to acc 052 * and recur! 053 */ 054 public String nonEmptyCase(INEList<? extends Object> host, String ... acc) { 055 return host.getRest().execute(this, acc[0] + ", " + host.getFirst()); 056 } 057 } 058