import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; /* * Sample_Visitor.java * * Created on Aug 25, 2007 * * by Donald Yessick */ /** * Sample_Visitor * @author Donald Yessick * printStream the ouput stream to write to * id a static counter of sampleVisitors */ public class Sample_Visitor implements CS220_Visitor_Interface { private static int cnt = 0; private int id = 0; private PrintStream printStream; /** * Default constructor -- sets print writer to System.out * */ Sample_Visitor(){ this.printStream = System.out; this.id = Sample_Visitor.cnt++; } /** * constructor -- sets print writer to a printStream (like System.out)t * @param printStream the PrintStream to print to */ Sample_Visitor(PrintStream printStream){ this.printStream = printStream; this.id = Sample_Visitor.cnt++; } /** * visit does something with an object, in this case it prints the object using the objects toString method. * @param object The object being visited * @see CS220_Visitor_Interface#visit(java.lang.Object) */ public void visit(Object object) { System.out.println(this.toString() + " is Visiting " + object.toString()); printStream.println(object.toString()); } public String toString(){ return "sample_Visitor #" +id; } /* * A test function for this visitor */ public static void main(String[] args) { System.out.println("Start Sample_Visitor Test:\n\targ.length=="+args.length + "\n\tfilename==\"TestOut_Sample_Visitor"+args.length+".txt\""); try { //creating two visitors //this one prints to standard out Sample_Visitor sample_Visitor = new Sample_Visitor(System.out); //this one prints to a file PrintStream printStream = new PrintStream("TestOut_Sample_Visitor"+args.length+".txt"); Sample_Visitor file_Visitor = new Sample_Visitor(printStream); //visit the arg strings for (int i=0; i < args.length; i++){ file_Visitor.visit(args[i]); } //the args might be empty so let's visit our sample_Visitor //(id # should be 0 or 3) file_Visitor.visit(sample_Visitor); //(id # should be 1 or 4) file_Visitor.visit(file_Visitor); //create a new Sample_Vistor and Visit it too sample_Visitor = new Sample_Visitor(System.out); //(id # should be 2 or 5) file_Visitor.visit(sample_Visitor); if (args.length == 0){ String[] params = {"one", "two", "three"}; Sample_Visitor.main( params ); } printStream.close(); } catch (Exception exception){ System.out.println("Error -- Exception thrown in Sample_Visitor"); exception.printStackTrace(System.err); System.exit(1); } System.out.println("End Sample_Visitor Test"); } }