Design Patterns Java™ Workbook

(Michael S) #1
Chapter 29. Visitor

To create a pretty-printer for processes, you can create a visitor class that initializes a
StringBuffer object and that adds to this buffer as the visitor visits the nodes in a process
component. To indicate that a composite step is an alternation, the visitor can prepend a
question mark (?) to an alternation step's name. To indicate that a step has occurred before,
the visitor can attach an ellipsis (...) to the end of the step's name.


A process component visitor has to watch for cycles, but this is easily achieved by using a
Set object to keep track of the nodes the visitor has already seen:


package com.oozinoz.dublin;
import java.util.;
import com.oozinoz.process.
;
public class PrettyVisitor implements ProcessVisitor
{
public static int INDENT_DEPTH = 4;
private StringBuffer buf;
private int depth;
private Set visited;


public StringBuffer getPretty(ProcessComponent pc)
{
buf = new StringBuffer();
visited = new HashSet();
depth = 0;
pc.accept(this);
return buf;
}


public void visit(ProcessAlternation a)
{
printComposite("?" + a.getName(), a);
}


public void visit(ProcessSequence s) {
printComposite(s.getName(), s);
}


public void visit(ProcessStep s) {
printTag(s.getName());
}


protected void printComposite(
String tag, ProcessComposite c)
{
if (visited.contains(c))
{
printTag(tag + "...");
}
else
{
visited.add(c);
printTag(tag);
acceptChildren(c);
}
}

Free download pdf