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.2. Implementing the Flyweight Pattern

Problem

You want to apply the flyweight pattern using AspectJ.

Solution

The flyweight pattern provides mechanisms by which fine-grained objects can be incorporated into an OO design without incurring a resource and performance penalty by sharing the objects where appropriate. A heavyweight object encapsulates the actual data to be referred to by potentially many flyweight objects.

The abstract aspect in Example 18-3 uses the Director aspect-oriented design pattern (see Chapter 23) to provide a template by which application specific aspects can apply the flyweight pattern.

Example 18-3. Using an abstract aspect to define the flyweight pattern

public abstract aspect FlyweightPattern 
{
   private Hashtable flyweightPool = new Hashtable( );

   public interface Flyweight
   {
   };  

   protected abstract pointcut flyweightCreation(Object key);

   Object around(Object key) : flyweightCreation(key) &&
      !within(com.oreilly.aspectjcookbook.oopatterns.FlyweightPattern+)
   {
      return this.checkFlyweight(key);
   }

   public synchronized Flyweight checkFlyweight(Object key)
   {
      if (flyweightPool.containsKey(key))
      {
        return (Flyweight) flyweightPool.get(key);
      }
      else
      {
        Flyweight flyweight = createNewFlyweight(key);
        flyweightPool.put(key, flyweight);
        return flyweight;
      }
   }

   protected abstract Flyweight createNewFlyweight(Object key);
}

Discussion

Figure 18-5 shows the structure of the FlyweightPattern abstract aspect and the interfaces and behavior that it defines to support the flyweight design ...

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