views:

394

answers:

2

Can anyone tell me how to implement the Strategy Pattern in AOP?

An example using Spring-AOP or AspectJ would be very helpful.

+4  A: 

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.

James Black
Why the downvote. It would be nice if someone knew that my answer is wrong to explain why.
James Black
A: 

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).

Rick
AOP can also be used to change behavior. For example, I have use AspectJ to turn a POJO into either a web service or a servlet, depending on the aspects. I would inject in the methods for HttpServlet for example, if I needed it.
James Black
@James Black: True, however I find using AOP to change behavior should not be considered implementing a strategy. You could use AOP to turn a entity into supporting the ActiveRecord pattern, however adding persistence with AOP is (perhaps good) separation of concern, however the used repositories using the AOP'ed objects could/should be a strategy.
Rick