Recipe 18.3. Implementing the Adapter PatternProblemYou want to apply the adapter pattern using AspectJ. SolutionThe adapter pattern provides a means of changing the message sent from one class to the message expected by the real destination class, adapting the messages to glue two classes together. Example 18-5 shows how to define an application specific adapter pattern aspect. Example 18-5. Adapting an existing class using aspectspublic aspect PrinterScreenAdapter { declare parents : Screen implements Printer; public void Screen.print(String s) { outputToScreen(s); } } DiscussionThe specific PrinterScreenAdapter aspect extends the behavior of the class that is to adapt to the new capabilities required of it by using AspectJ's capabilities to extend an existing class with new methods and potentially new parent classes, being careful at all times to respect the original capabilities of the class. Figure 18-8 shows the effects before and after the PrinterScreenAdapter aspect is applied to a Screen class that is adapted to support printing behavior. Figure 18-8. The effects of applying the adapter pattern to the Screen classSee AlsoThe recipes in Chapter 16 provide more information on how to extend existing classes and incorporate interfaces when defining aspects. |