Java Magazine, Sept/Oct 2018
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2018 70 design patterns optional Caption which is subclassed from TextNode and so on With all that structure in place its time to start to write visitors First suppose theres a requirement to print a quick draft of the document without trying to display the images this The iteration doesnt need to be a for loop or even an iterator any means of traversing all the nodes is fine capability was in the requirements from the days when graphics printers were expensive The text stored in a TextNode might contain more characters than fit on a line so I use an existing program called Fmt to crudely format lines to fit Fmt wants its input as a stream even though in this case its only one string so the visitTextNode method wraps the current TextNodes string in an array and streams that to the format method of Fmt static Visitor draftPrinterVisitor new Visitor @ Override public void visitTextNode TextNode textNode String lines textNode getText Fmt format Stream of lines out @ Override public void visitImageNode ImageNode imageNode String caption imageNode caption null imageNode caption getText no caption System out printf Image name s caption s n imageNode fileName caption The Fmt program requires a PrintWriter for output so the code on the following page wraps System out in a PrintWriter before passing the draftPrinterVisitor around to all the nodes
You must have JavaScript enabled to view digital editions.