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

18.1. Implementing the Composite Pattern

Problem

You want to apply the composite pattern using AspectJ.

Solution

The composite pattern provides the capability to group objects together in a collection and interact with the group as a whole in a similar manner as you would interact with an individual member of the group.

Example 18-1 uses the Director aspect-oriented design pattern (see Chapter 23) to provide a generic implementation of the composite pattern using AspectJ.

Example 18-1. Using an aspect to define the composite pattern

public abstract aspect CompositePattern 
{
   public interface Component 
   {
   }

   protected interface Composite extends Component 
   {
   }

   protected interface Leaf extends Component 
   {
   }

        private WeakHashMap perComponentChildren = new WeakHashMap( );

   private Vector getChildren(Component s) 
   {
      Vector children = (Vector) perComponentChildren.get(s);
      if (children == null) 
      {
         children = new Vector( );
         perComponentChildren.put(s, children);
      }
      return children;
   }

   public void addChild(Composite composite, Component component) 
   {
      getChildren(composite).add(component);
   }

   public void removeChild(Composite composite, Component component) 
   {
      getChildren(composite).remove(component);
   }

   public Enumeration getAllChildren(Component c) {
      return getChildren(c).elements( );
   }

   public interface Visitor {
      public void doOperation(Component c);
   }

   public void recurseOperation(Component c, Visitor v) { for (Enumeration enum = getAllChildren(c); enum.hasMoreElements( );) { Component child = (Component) ...

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