Recipe17.4.Implementing the Factory Method Pattern


Recipe 17.4. Implementing the Factory Method Pattern

Problem

You want to apply the factory method pattern using AspectJ.

Solution

The factory method pattern is similar to the abstract factory pattern in that it provides mechanisms by which the exact implementation of an object is decoupled from the clients of the factory. However, the factory method provides a single method for instantiating different implementations of a single interface.

The abstract class that contains the abstract factory method is implemented by specialized classes that explicitly override the factory method to provide mechanisms for instantiating different implementations of the desired object.

To implement the factory method pattern using AspectJ, use the same mechanisms as the abstract factory pattern to create an aspect that can remove the factory method pattern's reliance on an abstract base class using static cross-cutting techniques, providing a default implementation of the factory method or methods.

Discussion

A specialized aspect is shown in Example 17-6 that provides a default implementation for the factory method.

Example 17-6. Applying the factory method pattern using aspects
public interface ComputerCreator {            public Computer createComputer(String serial); } public aspect DefaultComputerCreatorImplementation  {    public void ComputerCreator.createComputerAndPrintInventory(String serial)    {       System.out.println("Inventory of computerparts:");       System.out.println(this.createComputer(serial).toString( ));    } }

Traditionally, the ComputerCreator interface in this solution would be an abstract class. However, static cross-cutting techniques can provide more freedom when applying the factory method design pattern by removing the need for the abstract base class.

See Also

Chapter 16 contains recipes that show static cross-cutting techniques for extending classes and providing default implementations of interface elements; Recipe 20.3 shows how to decouple the decision as to which implementation classes of an interface are instantiated solely 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