The Command pattern
Most applications nowadays have an undo operation. It is hard to imagine, but undo did not exist in any software for many years. Undo was introduced in 1974, but Fortran and Lisp, two programming languages that are still widely used, were created in 1957 and 1958, respectively! I wouldn’t like to have been an application user during those years. Making a mistake meant that the user had no easy way to fix it.
Enough with the history. We want to know how we can implement the undo functionality in our applications. Since you have read the title of this chapter, you already know which design pattern is recommended to implement undo: the Command pattern.
The Command design pattern helps us encapsulate an operation (undo, redo, copy, paste, and so forth) as an object. What this simply means is that we create a class that contains all the logic and the methods required to implement the operation. The advantages of doing this are as follows:
- We don...