Recipe19.9.Implementing the Template Method Pattern


Recipe 19.9. Implementing the Template Method Pattern

Problem

You want to apply the template pattern using AspectJ.

Solution

The template method pattern provides you with a mechanism by which to declare abstract methods within a generic work flow. These abstract steps or methods are implemented by specialized classes.

Example 19-17 shows how to apply the template method pattern using aspects.

Example 19-17. Defining the template method pattern using aspects
public interface AlgorithmDefinition {    public String runAlgorithm( );    public StringBuffer stepOne( );    public void stepTwo(StringBuffer data);    public void stepThree(StringBuffer data);    public String stepFour(StringBuffer data); } public aspect DefaultAlgorithmImplementation  {            public String AlgorithmDefinition.runAlgorithm( )    {       StringBuffer dataInProcess = this.stepOne( );       this.stepTwo(dataInProcess);       this.stepThree(dataInProcess);       return this.stepFour(dataInProcess);    }        public StringBuffer AlgorithmDefinition.stepOne( )    {       return new StringBuffer( );    }        public String AlgorithmDefinition.stepFour(StringBuffer data)    {       return data.toString( );    } }

Discussion

The DefaultAlgorithmImplementation aspect specifies the order of the steps for the algorithm and a default implementation for a couple of steps. By using aspect-oriented techniques, the algorithm template can be declared in an interface rather than an abstract class. Then, relying on static cross-cutting techniques, a default implementation of the appropriate generic steps, including the method to invoke the steps in the right order, can be specified in a concrete aspect. The more specific steps can be completed by the classes that implement the algorithm interface, automatically picking up on the default behavior where appropriate.

An aspect-oriented implementation advantage for this pattern is that it removes the constraint that the top-level class in the pattern must be an abstract class by moving the partial abstract implementation into the aspect and using static cross-cutting methods to provide that partial implementation by default on the interface. This leaves the design more flexible in that the concrete classes now implement the interface rather than using up their one inheritance relationship as allowed within Java to incorporate the pattern.

See Also

The recipes in Chapter 16 contain more details on the mechanisms by which existing classes can be extended using aspects.



AspectJ Cookbook
Aspectj Cookbook
ISBN: 0596006543
EAN: 2147483647
Year: 2006
Pages: 203
Authors: Russ Miles

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net