O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.8. Implementing the Visitor Pattern

Problem

You want to apply the visitor pattern using AspectJ.

Solution

The visitor pattern encapsulates a request that can be executed by a hierarchy of objects as it is passed throughout the structure. The abstract aspect in Example 19-15 uses the Director aspect-oriented design pattern (see Chapter 23) to define the roles that take part in the Visitor pattern.

Example 19-15. Defining the visitor pattern using aspects

public abstract aspect VisitorPattern 
{
   public interface Element
   {
      public void accept(Visitor visitor);
   }

   public interface CompositeElement extends Element
   {
      public Element[] getElements( );
   }

   public interface Result
   {
   }

   public interface Visitor
   {
      public void visitElement(Element element);
      public void visitComposite(CompositeElement element);
      public Result getResult( );
   }

   public void CompositeElement.accept(Visitor visitor)
   {
      visitor.visitComposite(this);
   }

   public void Element.accept(Visitor visitor)
   {
      visitor.visitElement(this);
   }
}

Discussion

The VisitorPattern abstract aspect defines the CompositeElement and Element roles as parts of the object structure that is to be visited. The Visitor role describes how the Visitor is notified of which type of element it is visiting. This role is applied to objects that may be passed to the different parts of the structure, be they composite or simple elements. The CompositeElement and Element roles are then extended to provide the methods by which the Visitor is passed.

Figure 19-26

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required