Recipe 16.3. Implementing Interfaces Using AspectsProblemYou want to add an interface to a class. SolutionUse the declare parents statement to specify a particular class that implements a specific interface or interfaces. DiscussionExample 16-3 shows how the declare parents statement in AspectJ can apply an interface to a class that may have had no knowledge of the interface prior to the aspect being applied. Example 16-3. Using aspects to declare a new interface on an existing classpublic aspect ImplementInterfaceRecipe { declare parents : MyClass implements MyInterface; } Figure 16-3 shows how the static class architecture is affected by the application of the aspect in Example 16-3. Figure 16-3. The static class structure before and after the aspect introduces a new interfaceHaving the capability to apply an interface to an existing class allows objects of that class to be referenced by the interface type, as shown in Example 16-4. Example 16-4. Referring to an object according to an aspect declared interface// Create an instance of MyClass MyInterface myObject = new MyClass( ); // ... // Work with the interface reference myObject.foo(1, "Russ"); By applying a new interface to a class, the class can be used in ways in which it was not originally designed. This is particularly useful when a new role is assigned to a class. The class must implement any methods the interface declares. In traditional object orientation, the Adapter design pattern would be a good solution. However, AspectJ does offer an alternative implementation of the Adapter pattern. Using the mechanisms shown in Recipe 12.1, an aspect can add implementations of the interfaces methods to the class without the need for a separate Adapter. See AlsoRecipe 16.1 shows how to extend an existing class with a new method; Chapter 17 through Chapter 19 give various examples of how roles can be assigned to classes using aspects when implementing OO design patterns; Recipe 18.3 discusses an aspect-oriented approach to implementing the Adapter design pattern; Recipe 23.2 shows how a generic design pattern for aspect-oriented role declaration. |