Can anyone tell me how to implement the Strategy Pattern in AOP?
An example using Spring-AOP or AspectJ would be very helpful.
Can anyone tell me how to implement the Strategy Pattern in AOP?
An example using Spring-AOP or AspectJ would be very helpful.
The easiest way I have found is to have your class implement a blank interface.
Then you use AspectJ to insert the implementation into the interface.
This way, if you need to change the algorithm you can just use a different aspect and the problem is solved.
To do this you can look at the manual on how to use inter-type: http://www.eclipse.org/aspectj/doc/released/progguide/starting-aspectj.html#inter-type-declarations
Update: Due to the downvote I am going to assume some people won't understand what I am talking about, so the easiest way is an example. This article has some nice examples of injecting methods into an interface. http://ramnivas.com/blog/index.php?p=20
This is not implementing the Strategy pattern, but the basic concept is the same, make it easy to switch from one algorithm to another, without changing any other part of the code. The only other way I can see of doing this is to use DI and just inject a new concrete class that each has the same interface for the Strategy, but that is outside of the question.
Update 2: Here are some links to show what can be done with AOP: Getting rid of design pattern density: http://www.ibm.com/developerworks/java/library/j-aopwork7/index.html Enhance Design patterns with AspectJ: http://www.ibm.com/developerworks/java/library/j-aopwork6/index.html AspectJ can be used for a great deal more than just some basic cross-cutting concerns. Most of the GoF design patterns can be easily implemented or retired by using AspectJ.
I think you got two things mixed up.
AOP is about implementing different aspects around the 'real' code. Like logging and validation. The logging itself could be implemented by using a DI container (like offered by spring) to really delegate the logging to the right implementation (strategy).