Question

I am currently taking a software design course. I myself have never been really good at designing software systems so I thought it was a smart move to patch up my weakness ;)

I am trying to understand how the command pattern works. I have looked all over for examples, but I am still puzzled. What are the responsibilities of each class in the pattern? Do ConcreteCommands actually perform the action or do they carry the information necessary and send it off to the appropriate destination to be actually executed?

Was it helpful?

Solution

Suppose you have a piece of paper with step-by-step instructions relative to some object. You put this paper into an envelope and seal it. Then you give the envelope to a friend of yours knowing that he will open it and do exactly what is written here when some event happen.

In this case you're a Client. The paper is a ConcreteCommand. Receiver is the object you mentioned in the paper. And Invoker is your friend.

You choose the conditions under which envelope will be opened by choosing the Invoker.

OTHER TIPS

There are two different variations on Command pattern that I have seen.

The first is a simple interface used to execute a task or command. The Runnable Java interface is one such example. Implementations have a simple method such as "doSomething()" that allows that task or command to be executed by another component in the system.

The textbook version of the Command pattern goes so far as to describe the other components of the system that will use the Command concrete implementation. This is where the other terms such as Invoker, Receiver and Client comes from. Refer to Wikipedia for more information on this: http://en.wikipedia.org/wiki/Command_pattern

Don't let this design pattern confuse you, its as simple as having an interface with a "doSomething()" definition.

As i understand it, the essence of Command pattern is to capture data for the action to be performed (so that it may be performed at the appropriate time, rather than immediately). Now who performs that action is not that important. It may be separate command handler class, or it may be the command class itself.

Speaking scientifically, the Command pattern is OO-implementation of closures from Functional Programming land, and should be used accordingly.

Suppose you have button control: when it pushed, some action should be performed. This action is ConcreteCommand. It could be plain pointer-to-function (in C or C++). But if it needs additional information from, for example, other controls or user input, they also should be captured somewhere. For this reason, it is convenient to have an object that would capture this additional information.

As a side effect, you can store Commands in some container and delay their execution, or you can track which Commands where executed, or you can rollback them later, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top