BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 2.0+

Command Design Pattern

The command pattern is a design pattern that enables all of the information for a request to be contained within a single object. The command can then be invoked as required, often as part of a batch of queued commands with rollback capabilities.

Testing the Command

To test the robot commands, we can use the Main method of a console application as the Client class of the design pattern. Add the following code to the Main method. This creates a queue of three commands and executes them. It then uses to undo function to reverse all three commands, returning the robot to its initial position and state. Execute the code to see the results.

Robot robot = new Robot();
RobotController controller = new RobotController();

MoveCommand move = new MoveCommand(robot);
move.ForwardDistance = 1000;
controller.Commands.Enqueue(move);

RotateCommand rotate = new RotateCommand(robot);
rotate.LeftRotation = 45;
controller.Commands.Enqueue(rotate);

ScoopCommand scoop = new ScoopCommand(robot);
scoop.ScoopUpwards = true;
controller.Commands.Enqueue(scoop);

controller.ExecuteCommands();
controller.UndoCommands(3);

/* OUTPUT

EXECUTING COMMANDS.
Robot moved forwards 1000mm.
Robot rotated left 45 degrees.
Robot gathered soil in scoop.
REVERSING 3 COMMAND(S).
Robot released scoop contents.
Robot rotated right 45 degrees.
Robot moved backwards 1000mm.

*/
9 August 2009