developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Compare Prices
Build a Server Rack
Logo Design
Condos For Sale
Career Education
Calling Cards
Phone Cards
Promos and Premiums
Baby Photo Contest
Promotional Pens
Promotional Golf
Rackmount LCD Monitor
Promotional Gifts
Memory

 
Biz Resources
Ecommerce Hosting
Dedicated Server Hosting
Data Recovery Services

Click Here
Web Devs:
Moonlight as a Game Developer and Win Cool Prizes by Accepting the RIA Run Challenge

Now, your mission--should you choose to accept: Take your shot at gaming stardom if you think you might have what it takes to build a cool RIA game and you could win an Xbox 360 or other fabulous prizes. Hurry! You only have until May 15, 2008 to enter. »

 
Article:
Leveraging Your Flash Development with Silverlight

You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. Learn more here. »

 
Article:
What Does it Take to Build the Best RIA?

With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »

 
Developer News -
SaaS Tool Offers Custom Database Development    May 9, 2008
Microsoft’s Automated Agent: Can We Talk?    May 7, 2008
Borland Finally Sells CodeGear    May 7, 2008
Red Hat Heads For The JON 2.0    May 7, 2008
Free Tech Newsletter -

Best Practices for Developing a Web Site: Checklists, Tips, Strategies & More. Download Exclusive eBook Now.

Working With Design Patterns: Visitor
By Jeff Langr

Go to page: 1  2  Next  

Suppose you want to navigate an object composite to produce a corresponding XML document. The problem is best solved recursively: Transform the root object's primitive fields into simple elements; then, navigate into each non-primitive field and similarly transform it.

Your best tactic is to split the problem into two: navigation of the object hierarchy, and transformation of Java elements into corresponding XML elements. Navigating the object hierarchy involves use of the Java reflection API. Producing the XML involves simple text manipulation. To adhere to the single responsibility principle (SRP), your solution thus requires two separate classes: a navigator class and a transformer class.

The visitor pattern provides one conforming solution, and also presents opportunities for reuse. The pattern refers to something that will be navigated, or visited, as an object structure. In the XML example, the object structure is simply your Java object structure as accessed via reflection. The visitor contains logic to execute upon visiting each pertinent element in the object structure. In the XML example, the visitor is the transform logic.

Basically, the visitor pattern is organized as a callback structure. The object structure accepts a reference to a visitor interface. Your XML transformer is one implementation of the visitor interface, but you could supply alternate implementations for different needs. As logic in the object structure navigates through the Java object hierarchy, it calls back to a method (conventionally named visit) on the visitor object.

Listing 1 presents a visitor interface for the XML example. Not only does it represent the callbacks for visiting an object, but also for departure and a visit to each primitive attribute in a Java object. (To keep the example simple, I omit logic for iterating collections.)

Listing 1: A visitor interface.

import util.*;

public interface Visitor {
   void visit(HierarchyObject instance);
   void visitPrimitiveAttribute(HierarchyObject instance,
                                HierarchyField attribute);
   void depart(HierarchyObject instance);
}

The HierarchyWalker class (see Listing 2) provides the high-level policy for navigating Java objects. This is the object structure representation for the visitor pattern. The walk method takes the object to be navigated and the visitor callback. The supporting classes, HierarchyObject (see Listing 3) and HierarchyField (see Listing 4), encapsulate the mildly gory details of Java reflection.

First things first. The walker visits each instance:

   visitor.visit(instance);

The walk method then iterates through each primitive attribute on the passed object:

   for (HierarchyField attribute: instance.primitiveAttributes())
      visitor.visitPrimitiveAttribute(instance, attribute);

The code then walks through each non-primitive, recursively calling the walk method, for each:

    for (HierarchyField attribute:
      instance.nonPrimitiveAttributes())
      walk(attribute.getValue(object), visitor);

Finally, the walk method calls the depart method on the visitor.

   visitor.depart(instance);

Listing 2: HierarchyWalker.

import util.*;

public class HierarchyWalker {
   public void walk(Object object, Visitor visitor) {
      HierarchyObject instance = new HierarchyObject(object);
      visitor.visit(instance);
      for (HierarchyField attribute:
         instance.primitiveAttributes())
         visitor.visitPrimitiveAttribute(instance, attribute);
      for (HierarchyField attribute:
         instance.nonPrimitiveAttributes())
         walk(attribute.getValue(object), visitor);
      visitor.depart(instance);
   }
}

Listing 3: HierarchyObject.

import java.lang.reflect.*;
import java.util.*;

public class HierarchyObject {
   private Object object;

   public HierarchyObject(Object object) {
      this.object = object;
   }

   public String typeName() {
      return object.getClass().getSimpleName();
   }

   public Collection<HierarchyField> primitiveAttributes() {
      Collection<HierarchyField> attributes =
         new ArrayList<HierarchyField>();
      for (Field field: attributeFields())
         if (isPrimitiveOrString(field))
            attributes.add(new HierarchyField(field));
      return attributes;
   }

   public Collection<HierarchyField> nonPrimitiveAttributes() {
      Collection<HierarchyField> attributes =
         new ArrayList<HierarchyField>();
      for (Field field: attributeFields())
         if (!isPrimitiveOrString(field))
            attributes.add(new HierarchyField(field));
      return attributes;
   }

   private Field[] attributeFields() {
      return object.getClass().getDeclaredFields();
   }

   public Object getObject() {
      return object;
   }

   private boolean isPrimitiveOrString(Field field) {
      return field.getType().isPrimitive() ||
         field.getType() == String.class;
   }

   public String valueString(HierarchyField attribute) {
      return attribute.getValue(object).toString();
   }
}

Go to page: 1  2  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Architecture & Design Archives

Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation
Whitepaper: Embeddable Content Platform for OEM's
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Generate Complete .NET Web Apps in Minutes . Download Iron Speed Designer today.
Is it time to make your move to the multi-threaded and parallel processing world? Find out!



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES