The Evolution of Command Pattern (I)
How Command Pattern has evolved overtime
The Command Pattern is one of my favourite design patterns. It is also a good example that design patterns do change over time. In part I, we talk about the original version from the Design Patterns book.
This pattern first appears in the famous GoF book, described as follows:
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
This definition may seem confusing if you are new to it, let’s see a simple example.
Suppose we are building a PhotoShop like software. But since we are so innovative and believe in simplistic design, it has only two buttons, a circle button and a rectangle, and a white canvas. When pressed, the buttons draw a circle or a rectangle on the canvas. And user can also undo the drawing.
The key concept of this pattern is the Command
abstract class, it looks like this.
Notice every command has two operations, execute()
and undo()
.
Now we can use it to model the drawings as different commands.
Notice when create the concrete drawing command, we pass in a Canvas
for it to draw on.
Now the two commands look quite the same, the only different part is one draws a Circle
one draws a Rectangle
. So we can refactor out the common parts.
And in the Main
part of the program, we can just create a bunch of commands and execute or undo them.
Imagine we can create these commands and put them in the buttons, and when the user presses the button, the button just execute its command.
There are 2 benefits of doing this:
- The button doesn’t need to know the details of the commands associated with it, it only cares one thing, which is how to execute it (or undo it).
- We can change the behavior of the buttons very easily but configure them with different commands, and the button itself doesn’t need to be changed.
Here is the rest of the code if you want to run it yourself.
We can go very far with this pattern, we can actually design the whole system based on this pattern. In this book Agile Software Development Principles Patterns and Practices by Uncle Bob, it gives a very good example of how to design a payroll system by using command pattern in Chapter 12. The code in the book is in C++, I ported it to Java here.
This wraps up the discussion about the original Command Pattern. In next part, we will talk about a more complicated version of it, stay tuned.
Share this post
Twitter
Google+
Facebook
Reddit
LinkedIn
StumbleUpon
Email