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

Problem

You want to apply the strategy pattern using AspectJ.

Solution

The strategy pattern provides a mechanism to separate client classes from the actual implementation details of a particular algorithm or strategy. Traditionally, all of the separate classes, which implement the strategy, implemented a distinct interface to allow the client to be decoupled from the different implementations.

The abstract aspect in Example 19-13 uses the Director aspect-oriented design pattern (see Chapter 23) to provide a generic implementation of the strategy pattern that can be applied to your application.

Example 19-13. Defining the strategy pattern using aspects

public abstract aspect StrategyPattern 
{
   Hashtable strategyPerContext = new Hashtable( );

   protected interface Strategy
   {
   }

   protected interface Context
   {
   }

   private Strategy Context.strategy = null;

   public void setConcreteStrategy(Context c, Strategy s)
   {
      strategyPerContext.put(c, s);
   }

   public Strategy getConcreteStrategy(Context c)
   {
      return (Strategy) strategyPerContext.get(c);
   }
}

Discussion

The StrategyPattern abstract provides definitions of the Strategy and Context roles as interfaces. A hash table is used to look up the specific concrete strategy to be used.

Figure 19-22 shows the structure of the StrategyPattern abstract aspect and the interfaces and behavior that it defines to support the strategy design pattern.

Figure 19-22. The StrategyPattern aspect and the interfaces it defines for the 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