Pattern: Command Interceptor
Problem
How can one transparently extend the behaviour of a predefined scripting command?
Context
Your script is using a command but the behaviour of that command is not quite what is needed. Defining a new command with another name is not possible, possibly because the command is used by other code over which you have no control and you must change the behaviour of the command for all code that uses it.
Your scripting language allows scripts to rename commands.
Forces
- You must add behaviour to a predefined command.
- You don't want to, or cannot, change all code that uses the command.
Solution
Rename the command you want to change with a new, unique, name. Define a new command with the original name of the command you have just renamed. This new command should call the original command via its new name but can perform preprocessing before the call and postprocessing after the call.
Consequences
The command has been extended with additional behaviour.
The new behaviour is invoked by code that was written without knowledge of the changes.
This technique can be applied multiple times without problem, thereby creating a Chain of Responsibility.
A Command Interceptor can break code that relies on the old implementation of the command if the post-processing step returns unexpected values.
Known Uses
The Tcl/Tk idioms At-Exit Callback and Widget Facade are both examples of Command Interceptors.
Nat Pryce (np2@doc.ic.ac.uk)