Quantcast
Channel: Free practice test , mock test, driving test, interview questions » design patterns
Viewing all articles
Browse latest Browse all 10

Command Design Pattern

$
0
0

Problem

How can we issue request to other objects in a system, without having to know who will receive the request, or even what the request is? This can be useful for implementing functionality such as a menu system, where each menu item has a command that it executes, but it doesn’t want to know what it is, it only needs to trigger the command at the right time. How can this be done?

Solution

The command pattern is simple the use of objects as commands in a system. The command class has a virtual member called Execute(). In our above example, the menu item could take a command object as an initialization parameter, and when the application runs, then menu item gets a command, the when the menu item is clicked it calls Execute() on the command.

Consequences

Commands are very powerful, and can support a lot of different functionality. For example, if the command registered itself with some global undo class when it executes, then simply by reversing each command in reverse order (I smell a stack…) we can undo any sequence of commands provided every command class can be undone. Command object separates the object that triggers an operation from the one that executes the operation. By using the Composite pattern you can extend a command to execute multiple commands. And since all commands derive from the command base class, adding new commands is easy.

I myself have used this pattern to implement a dynamic console in a game. At run-time, sections of code register commands into the console. The console then accepts textual input, and pattern matches against a Name() method of each command, and upon finding a match it calls Execute() on the command. I had implemented this before discovering Design Patterns, so could have saved myself a lot of work in knowing the intricacies of this pattern if I had read the book.


Viewing all articles
Browse latest Browse all 10

Trending Articles