
Last week we covered how we'd implement the decorator pattern in Java to solve how to modify the behavior of an existing class without modifying or subclassing it. It turns out that implementing this behavior is even simpler in AspectJ.For a refresher on the decorator pattern, read the preceding post.
As before, say we have a Car class which has some functionality we'd like to modify, say by adding a top to the car or an engine. Listing 1 shows a Car interface and SimpleCar class.
Listing 1: Car Interface and SimpleCar Class
To add a top or an engine, we'd need separate classes for each functionality, and an abstract class that they extend. But instead, we can just add two aspects (see Listing 2).
Each aspect modifies the code so that it performs some behavior prior to calling drive(), and it modifies the getInfo method. Both aspects total twelve lines of code (not including braces), whereas the equivalent code in Java totals nearly double the lines at twenty-two.
We can view the results of the Decorator pattern by calling the getInfo method, which should return "car, with top, with revved engine".
Line three is very straightforward, whereas the equivalent line in the Java-only implementation is a bit more convoluted, as each constructor must be called for each class. For multiple classes, it can be quite unwieldy.
This is a bit perfect example of using AspectJ's interception capabilities to add a crosscutting concern. In a more realistic example, Car could be a communication class, and TopAspect could be a logger, while EngineAspect could be an encryption engine. In this way, Car could be written without "concern" for logic unrelated to itself, and these new aspects could be added later.
Erhan J. Kartaltepe,
erhan.kartaltepe-at-utsa.edu





