Designing with Patterns

   

This is where the interesting part begins. Your goal is to read the XML file in Listing 1.7 in the object structure outlined in Figure 1.3.

The simplest solution is to add methods to the various classes to read and write the XML document. A method to read a Description might look similar to

 public static Description readXML(Element element)    {       if(element.getTagName().equals("Text"))       {          String text = null;          Node child = element.getFirstChild();          if(child != null &&             child.getNodeType() == Node.TEXT_NODE)          {             Text t = (Text)child;             text = t.getData();          }          String language = element.getAttribute("xml:lang");          return new Description(language,text);       }       else          return null;    } 

Note that this method relies on a DOM (Document Object Model) parser to handle the XML syntax. So, the Element parameter is a DOM Element object.

The method to write a Description object in XML would be as follows :

 public void writeXML(PrintWriter pw)       throws IOException    {       pw.print("<Text xml:lang='" + language + "'>");       pw.print(text);       pw.println("</Text>");    } 

This is simple, but it is also limited. First, it mixes the XML into the data structure, which greatly limits your ability to evolve one independently from the other. It also spreads the XML code over the entire object hierarchy, which makes it more difficult to maintain.

We can do better using two patterns, the builder pattern and the visitor pattern, as described in Design Patterns by Gamma, et al. (Addison-Wesley).

Use these patterns to separate the XML- related code from the object structure so that you can change the file format without having to change your objects or vice versa.

   


Applied XML Solutions
Applied XML Solutions
ISBN: 0672320541
EAN: 2147483647
Year: 1999
Pages: 142

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net