A lot of folks who don’t know enough about AOP (Aspect Oriented Programming) feel that they can achieve the same results by using the decorator pattern. While AOP is similar in concept, there is a lot more that AOP can solve that a decorator pattern would be hard pressed to do. The GOF Decorator pattern requires either that some method be directly called or that the code that is decorated implements some common interface. This works if:
- You have control of the code base and/or architecture
- You only want to decorate a specific base class or interface
The pattern doesn’t work to well when have to start decorating classes that don’t adhere to the aforementioned conditions. You know, when those “new” requirements start trickling in after the the application has launched. And as usual, the requirements don’t quite mesh well with the existing architecture.
Keep in mind that I’m not advocating using AOP to compensate for a crappy architecture, but it sure can help🙂. But seriously, you can’t think of everything in your design phase. Eventually, someone is going throw you a curve that your design didn’t count on. I recently came across a problem in a reporting application where we needed to find out what some of the intermediate calculations were in order to debug a problem. The application was never designed to write out all of these values, since they would have been discarded anyway. Additionally, modifying the code would have taken a few days and potentially destabilized the code base. I ended up using JBoss AOP (note: not the app server) to write a few interceptors that collected these values. The application ran as normal, but these intermediate calculations were now captured. All was good, and it took me less than a day to implement.
My point is, a decorator pattern isn’t always feasible. I couldn’t retrofit a decorator pattern onto this app to do what I needed to do in such a short time frame. Sure AOP is a decorator in the abstract sense, but you can’t do everything with a decorator that AOP can.