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.2. Implementing the Command Pattern

Problem

You want to apply the command pattern using AspectJ.

Solution

The command design pattern supports the encapsulation of requests as objects within their own right. Single or multiple operations can be combined into a request or transaction depending on their purpose. Once the request object has been constructed, it can be managed as a separate entity from the originating object.

Example 19-3 uses the Director aspect-oriented design pattern (see Chapter 23) to provide an abstract aspect that can be used to apply the command pattern.

Example 19-3. Defining the command pattern using aspects

public abstract aspect CommandPattern { public interface Command { public void executeCommand(CommandReceiver receiver); public boolean isExecutable( ); } public interface CommandInvoker { } public interface CommandReceiver { } private WeakHashMap mappingInvokerToCommand = new WeakHashMap( ); public Object setCommand(CommandInvoker invoker, Command command) { return mappingInvokerToCommand.put(invoker, command); } public Object removeCommand(CommandInvoker invoker) { return setCommand(invoker, null); } public Command getCommand(CommandInvoker invoker) { return (Command) mappingInvokerToCommand.get(invoker); } private WeakHashMap mappingCommandToReceiver = new WeakHashMap( ); public Object setReceiver(Command command, CommandReceiver receiver) { return mappingCommandToReceiver.put(command, receiver); } public CommandReceiver getReceiver(Command command) { ...

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