The command interface offers one methods:
Both methods have the following behavior:
- The business logic is implemented in this methods.
- If something fails,
- If something fails,
- If everything is alright,
These methods are made for executing either standalone or in a chain, which runs until one Command fails or throws an exception.
ChainCommand objects has additional methods:
The behavior of
executeCommandAsChain() is quite different to the usual
executeCommand() method. In this case the command is aware of the chain and can decide if the whole work of the chain is done or if the next link of the chain should overtake.
For this the
- NEXT work is done, the next chain can overtake.
- DONE if everything is fine and the work of the whole chain is done.
- FAILURE if an error occurred and it makes no sense, that the next command should overtake.
The last situation often comes if the first command should load a resource and the resource is not available. In this case it makes no sense to continue.
If you look in the
AbstractDefaultChainCommand class you see a translation between command and chain which might be confusing:
A Command result of
SUCCESS means: Everything was OK, the next command can be triggered even a
FAILURE means that an exception has occurred and the execution of the chain should be stopped. This means: If the whole logic is encapsulated in the
executeCommand() method, sometimes the command has to return
FAILURE, even everything is OK, because in terms of
FAILURE sometimes the next command has to overtake.. So it might be a good approach as well leaving the
executeCommand() method blank and implement the logic in the
CommandContainer object couple commands together. The execution of commands works as follow:
execute()works as long as no command throws an exception. An exception does not stop the whole chain. (removed in 1.6.0)
executeCommand()has the same behavior. Instead of throwing an exception
executeAsChain()simulates the chain of responsibility design pattern. As long as commands returns true, the execution will not stop. (removed in 1.6.0)
executeCommandAsChain()has the same behavior but the return value is either NEXT (next command should overtake), DONE (work is done) or
FAILURE, some error occurred and stops the whole chain.
CommandContainer object is a
Command as well you can add
CommandContainer as well in a single container. In addition you've methods to order Command objects in the container via priority. If two
Command objects share the same priority the first inserted
Command will win. Browse the java doc to go in depth.