Undo Method


Undo Method

Figure 21-6 adds the Undo() method to the COMMAND pattern. It stands to reason that if the Execute() method of a Command derivative can be implemented to remember the details of the operation it performs, the Undo() method can be implemented to undo that operation and return the system to its original state.

Figure 21-6. Undo variation of the COMMAND pattern


Imagine, for example, an application that allows the user to draw geometric shapes on the screen. A toolbar has buttons that allow the user to draw circles, squares, rectangles, and so on. Let's say that the user clicks the Draw Circle button. The system creates a DrawCircleCommand and then calls Execute() on that command. The DrawCircleCommand object tracks the user's mouse, waiting for a click in the drawing window. On receiving that click, it sets the click point as the center of the circle and proceeds to draw an animated circle at that center, with a radius that tracks the current mouse position. When the user clicks again, the DrawCircleCommand stops animating the circle and adds the appropriate circle object to the list of shapes currently displayed on the canvas. It also stores the ID of the new circle in a private variable of its own. Then it returns from the Execute() method. The system then pushes the expended DrawCirlceCommand on the stack of completed commands.

Some time later, the user clicks the Undo button on the toolbar. The system pops the completed commands stack and calls Undo() on the resulting Command object. On receiving the Undo() message, the DrawCircleCommand object deletes the circle matching the saved ID from the list of objects currently displayed on the canvas.

With this technique, you can easily implement Undo in nearly any application. The code that knows how to undo a command is always right next to the code that knows how to perform the command.




Agile Principles, Patterns, and Practices in C#
Agile Principles, Patterns, and Practices in C#
ISBN: 0131857258
EAN: 2147483647
Year: 2006
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net