O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.5. Implementing the Chain of Responsibility Pattern

Problem

You want to apply the chain of responsibility pattern using AspectJ.

Solution

The chain of responsibility pattern allows the separation of the source of a request from deciding which of the potentially large number of handlers for the request should action it. The class representing the chain role channels the requests from the source along the list of handlers until a handler accepts the request and actions it.

The abstract aspect in Example 19-9 uses the Director aspect-oriented design pattern (see Chapter 23) to provide the generic mechanisms by which the chain of responsibility pattern can be applied to an application. The decision as to what occurs if none of the available handlers in the chain accept the request is an application-specific decision; although a default behavior is implemented in the abstract aspect, this can be overridden by extending implementations.

Example 19-9. Defining the chain of responsibility pattern using aspects

public abstract aspect ChainOfResponsibilityPattern { protected interface Handler { } public WeakHashMap successors = new WeakHashMap( ); protected void receiveRequest(Handler handler, Object request) { if (handler.acceptRequest(request)) { handler.handleRequest(request); } else { // The handler will not accept the request Handler successor = getSuccessor(handler); if (successor == null) { // Last handler in the chain so must deal with the request // This is a rudimentary implementation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required