The Command Design Pattern

Today I am looking at another design pattern. This one is the command design pattern, which is yet another Gang of Four design. They classify it as a behavioral pattern with object as the scope (GoF 223). I wanted to explore this one as reading through the different pattern descriptions in the Gang of Four book, this peaked my interested by its ability to separate requests from objects. The article gives a good summary of the idea of the pattern with a real-life example of a restaurant with a server taking an order from a customer and handing it off to a chef. It then further breaks down the pattern with the usual UML diagram and a helpful sequence diagram that shows the order in which the classes perform the pattern. I found this sequence diagram, along with the comments in the example program with code that show which class matches with which part of the diagrams really useful in this example, as the pattern goes through a couple of classes just to call a basic function on a simple object. Although this pattern does seem complex at first, it has a nice simplicity once you understand what all the classes are doing, and once you get the base created adding more functions is as simple as adding more command classes. The article then creates a simple example with Java of the command pattern using the various classes to switch a light bulb object on and off. I do like the idea of the pattern and its particular implementation in this example. It nicely breaks down requests into their own separate command objects that gives much greater control over requests across a program. I agree that the ability this pattern gives to create a log of function calls and add an ability to undo all functions called on an object is very helpful. I also agree with the author that it can get messy if you have a lot of functions that need to be implemented. As this pattern calls for a separate command class to be made for each function or method performed on an object, this can quickly add up depending on how many methods you need in your program. In the future, I will definitely remember this pattern and its useful ability to separate commands from the objects it performs them on.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s