Open main menu

CDOT Wiki β

Command

Revision as of 19:43, 25 March 2007 by Ermarinz (talk | contribs) (Introduction)

Introduction

The Command Pattern

The idea behind the Command pattern is to encapsulate code that performs specific 'command-like' tasks for an application. A very important part of the command pattern is the abstract command class, which defines an interface to code to. In this class there is an execute operation. When a concrete command class is created, all of the code for one speciffic command goes into this execute operation and runs when it is called.

A good example to mention right from the beginning to help you understand the command pattern quicker is the menu bar at the top of this web browser. The command pattern may very well have been used in the design of this. Go up to the menu and click on 'File'. A bunch of options fly down (obviously). Each of these options could be implementations of the command class. New Window, for example, would call the execute operation when clicked and the code inside there would do whatever it has to do to pop open a fresh new browser. Each other option invokes it's own command(s) when clicked. That 's' is in brackets because since the command class is an object, a command can contain and execute multiple commands per single execution. This is also known as a Macro, and you can create macros with ease with the command pattern. Undo / re-do operations, log files, and other commonly used commands are also easily implemented with the command pattern.

UML Diagram

 

Practical Example

Code Examples

Java

C++