Command pattern
Encyclopedia
In object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, the command pattern is a design pattern
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...

 in which an object is used to represent and encapsulate
Information hiding
In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...

 all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Three terms always associated with the command pattern are client, invoker and receiver. The client instantiates the command object and provides the information required to call the method at a later time. The invoker decides when the method should be called. The receiver is an instance of the class that contains the method's code.

Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters.

Uses

Command objects are useful for implementing:

Multi-level undo
Undo
Undo is a command in many computer programs. It erases the last change done to the document reverting it to an older state. In some more advanced programs such as graphic processing, undo will negate the last command done to the file being edited....

 : If all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo method.
Transactional
Database transaction
A transaction comprises a unit of work performed within a database management system against a database, and treated in a coherent and reliable way independent of other transactions...

 behavior : Similar to undo, a database engine or software installer may keep a list of operations that have been or will be performed. Should one of them fail, all others can be reverted or discarded (usually called rollback). For example, if two database tables which refer to each other must be updated, and the second update fails, the transaction can be rolled back, so that the first table does not now contain an invalid reference.
Progress bar
Progress bar
A progress bar is a component in a graphical user interface used to convey the progress of a task, such as a download or file transfer. Often, the graphic is accompanied by a textual representation of the progress in a percent format....

s : Suppose a program has a sequence of commands that it executes in order. If each command object has a getEstimatedDuration method, the program can easily estimate the total duration. It can show a progress bar that meaningfully reflects how close the program is to completing all the tasks.
Wizard
Wizard (software)
A software wizard or setup assistant is a user interface type that presents a user with a sequence of dialog boxes that lead the user through a series of well-defined steps. Tasks that are complex, infrequently performed, or unfamiliar may be easier to perform using a wizard...

s : Often a wizard presents several pages of configuration for a single action that happens only when the user clicks the "Finish" button on the last page. In these cases, a natural way to separate user interface code from application code is to implement the wizard using a command object. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses. "Finish" simply triggers a call to execute. This way, the command class contains no user interface code.
GUI buttons and menu items : In Swing
Swing (Java)
Swing is the primary Java GUI widget toolkit. It is part of Oracle's Java Foundation Classes — an API for providing a graphical user interface for Java programs....

 and Borland Delphi
Borland Delphi
Embarcadero Delphi is an integrated development environment for console, desktop graphical, web, and mobile applications.Delphi's compilers use its own Object Pascal dialect of Pascal and generate native code for 32- and 64-bit Windows operating systems, as well as 32-bit Mac OS X and iOS...

 programming, an is a command object. In addition to the ability to perform the desired command, an Action may have an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only the Action object.
Thread pools : A typical, general-purpose thread pool class might have a public addTask method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. The items in the queue are command objects. Typically these objects implement a common interface such as java.lang.Runnable that allows the thread pool to execute the command even though the thread pool class itself was written without any knowledge of the specific tasks for which it would be used.
Macro recording : If all user actions are represented by command objects, a program can record a sequence of actions simply by keeping a list of the command objects as they are executed. It can then "play back" the same actions by executing the same command objects again in sequence. If the program embeds a scripting engine, each command object can implement a toScript method, and user actions can then be easily recorded as scripts.
Networking : It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games.
Parallel Processing : Where the commands are written as tasks to a shared resource and executed by many threads in parallel (possibly on remote machines -this variant is often referred to as the Master/Worker pattern)
Mobile Code
Code Mobility
In distributed computing, code mobility is the ability for running programs, codes or objects to be migrated from one machine to another. This is the process of moving code across the nodes of a network as opposed to distributed computation where the data is moved...

 : Using languages such as Java where code can be streamed/slurped from one location to another via URLClassloaders and Codebases the commands can enable new behavior to be delivered to remote locations (EJB Command, Master Worker)

Structure


  • The explanation for the Receiver block above should be "The actual work to be done by the command (action)"

Terminology

The terminology used to describe command pattern implementations is not consistent and can therefore be confusing.
This is the result of ambiguity
Ambiguity
Ambiguity of words or phrases is the ability to express more than one interpretation. It is distinct from vagueness, which is a statement about the lack of precision contained or available in the information.Context may play a role in resolving ambiguity...

, the use of synonyms, and implementations that may obscure the original pattern by going well beyond it.
  1. Ambiguity.
    1. The term command is ambiguous. For example, move up, move up may refer to a single (move up) command that should be executed twice, or it may refer to two commands, each of which happens to do the same thing (move up). If the former command is added twice to an undo stack, both items on the stack refer to the same command instance. This may be appropriate when a command can always be undone the same way (e.g. move down). Both the Gang of Four and the Java example below use this interpretation of the term command. On the other hand, if the latter commands are added to an undo stack, the stack refers to two separate objects. This may be appropriate when each object on the stack must contain information that allows the command to be undone. For example, to undo a delete selection command, the object may contain a copy of the deleted text so that it can be re-inserted if the delete selection command must be undone. Note that using a separate object for each invocation of a command is also an example of the chain of responsibility pattern.
    2. The term execute is also ambiguous. It may refer to running the code identified by the command object's execute method. However, in Microsoft's Windows Presentation Foundation
      Windows Presentation Foundation
      Developed by Microsoft, the Windows Presentation Foundation is a computer-software graphical subsystem for rendering user interfaces in Windows-based applications. WPF, previously known as "Avalon", was initially released as part of .NET Framework 3.0. Rather than relying on the older GDI...

       a command is considered to have been executed when the command's execute method has been invoked, but that does not necessarily mean that the application code has run. That occurs only after some further event processing.
  2. Synonyms and homonyms.
    1. Client, Source, Invoker: the button, toolbar button, or menu item clicked, the shortcut key pressed by the user.
    2. Command Object, Routed Command Object, Action Object: a singleton object (e.g. there is only one CopyCommand object), which knows about shortcut keys, button images, command text, etc. related to the command. A source/invoker object calls the Command/Action object's execute/performAction method. The Command/Action object notifies the appropriate source/invoker objects when the availability of a command/action has changed. This allows buttons and menu items to become inactive (grayed out) when a command/action cannot be executed/performed.
    3. Receiver, Target Object: the object that is about to be copied, pasted, moved, etc. The receiver object owns the method that is called by the command's execute method. The receiver is typically also the target object. For example, if the receiver object is a cursor and the method is called moveUp, then one would expect that the cursor is the target of the moveUp action. On the other hand, if the code is defined by the command object itself, the target object will be a different object entirely.
    4. Command Object, routed event args, event object: the object that is passed from the source to the Command/Action object, to the Target object to the code that does the work. Each button click or shortcut key results in a new command/event object. Some implementations add more information to the command/event object as it is being passed from one object (e.g. CopyCommand) to another (e.g. document section). Other implementations put command/event objects in other event objects (like a box inside a bigger box) as they move along the line, to avoid naming conflicts. (See also chain of responsibility pattern).
    5. Handler, ExecutedRoutedEventHandler, method, function: the actual code that does the copying, pasting, moving, etc. In some implementations the handler code is part of the command/action object. In other implementations the code is part of the Receiver/Target Object, and in yet other implementations the handler code is kept separate from the other objects.
    6. Command Manager, Undo Manager, Scheduler, Queue, Dispatcher, Invoker: an object that puts command/event objects on an undo stack or redo stack, or that holds on to command/event objects until other objects are ready to act on them, or that routes the command/event objects to the appropriate receiver/target object or handler code.
  3. Implementations that go well beyond the original command pattern.
    1. Microsoft's Windows Presentation Foundation (WPF), introduces routed commands, which combine the command pattern with event processing. As a result the command object no longer contains a reference to the target object nor a reference to the application code. Instead, invoking the command object's execute command results in a so called Executed Routed Event which during the event's tunneling or bubbling may encounter a so called binding object which identifies the target and the application code, which is executed at that point.

Example

Consider a "simple" switch. In this example we configure the Switch with 2 commands: to turn the light on and to turn the light off.

A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light - the Switch in the following example turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its 2 parameters. For example, you could configure the Switch to start an engine.

Note: A criticism of the sample application below is that it doesn't truly model an electrical circuit. An electrical switch is dumb. A true binary switch knows only that it is either on or off. It does not know about or have any direct relationship with the various loads that might be attached to a circuit (i.e. you hook up a switch to a circuit, not directly to a load). The switch should simply publish an event of its current state (either an ON or OFF). The circuit then should contain a State Engine which manages circuit states at various points along it (by listening to switch events) in order to properly accommodate complex circuits with multiple loads and switches. Each load is then conditional to a specific circuit's state (not directly to any specific switch). In conclusion, the switch itself should not be aware of any lamp details.


/* The Invoker class */
public class Switch {

private Command flipUpCommand;
private Command flipDownCommand;

public Switch(Command flipUpCmd, Command flipDownCmd) {
this.flipUpCommand = flipUpCmd;
this.flipDownCommand = flipDownCmd;
}

public void flipUp {
flipUpCommand.execute;
}

public void flipDown {
flipDownCommand.execute;
}
}

/* The Receiver class */
public class Light {

public Light { }

public void turnOn {
System.out.println("The light is on");
}

public void turnOff {
System.out.println("The light is off");
}
}

/* The Command interface */
public interface Command {
void execute;
}

/* The Command for turning the light on in North America, or turning the light off in most other places */
public class FlipUpCommand implements Command {

private Light theLight;

public FlipUpCommand(Light light) {
this.theLight = light;
}

public void execute{
theLight.turnOn;
}
}

/* The Command for turning the light off in North America, or turning the light on in most other places */
public class FlipDownCommand implements Command {

private Light theLight;

public FlipDownCommand(Light light) {
this.theLight = light;
}

public void execute {
theLight.turnOff;
}
}

/* The test class or client */
public class PressSwitch {

public static void main(String[] args) {
Light lamp = new Light;
Command switchUp = new FlipUpCommand(lamp);
Command switchDown = new FlipDownCommand(lamp);

// See criticism of this model above:
// The switch itself should not be aware of lamp details (switchUp, switchDown)
// either directly or indirectly
Switch s = new Switch(switchUp, switchDown);

try {
if (args[0].equalsIgnoreCase("ON")) {
s.flipUp;
} else if (args[0].equalsIgnoreCase("OFF")) {
s.flipDown;
} else {
System.out.println("Argument \"ON\" or \"OFF\" is required.");
}
} catch (Exception e) {
System.out.println("Arguments required.");
}
}
}




class Switch:
""" The INVOKER class"""
def __init__(self, flipUpCmd, flipDownCmd):
self.__flipUpCommand = flipUpCmd
self.__flipDownCommand = flipDownCmd
def flipUp(self):
self.__flipUpCommand.execute
def flipDown(self):
self.__flipDownCommand.execute

class Light:
"""The RECEIVER Class"""
def turnOn(self):
print "The light is on"
def turnOff(self):
print "The light is off"

class Command:
"""The Command Abstract class"""
def __init__(self):
pass

def execute(self):
pass

class FlipUpCommand(Command):
"""The Command class for turning on the light"""
def __init__(self,light):
self.__light = light
def execute(self):
self.__light.turnOn
class FlipDownCommand(Command):
"""The Command class for turning off the light"""
def __init__(self,light):
Command.__init__(self)
self.__light = light
def execute(self):
self.__light.turnOff

class LightSwitch:
""" The Client Class"""
def __init__(self):
self.__lamp = Light
self.__switchUp = FlipUpCommand(self.__lamp)
self.__switchDown = FlipDownCommand(self.__lamp)
self.__switch = Switch(self.__switchUp,self.__switchDown)
def switch(self,cmd):
cmd = cmd.strip.upper
try:
if cmd

"ON":
self.__switch.flipUp
elif cmd

"OFF":
self.__switch.flipDown
else:
print "Argument \"ON\" or \"OFF\" is required."
except Exception, msg:
print "Exception occurred: %s" % msg
  1. Execute if this file is run as a script and not imported as a module


if __name__

"__main__":
lightSwitch = LightSwitch
print "Switch ON test."
lightSwitch.switch("ON")
print "Switch OFF test"
lightSwitch.switch("OFF")
print "Invalid Command test"
lightSwitch.switch("****")

See also

  • Batch queue
    Batch queue
    A batch queue, sometimes also known as job queue, is a system software data structuremaintained by job scheduler software.Users submit their programs that they want executed, "jobs", to the queue for batch processing....

  • Closure
    Closure (computer science)
    In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...

  • Command queue
    Command queue
    A command queue is a queue for delaying the execution of commands, usually either in order of priority or on a first-in first-out basis. They are often useful in synchronous applications, where a command executor may receive a new command while it is still performing a previous one, and so requires...

  • Function object
    Function object
    A function object, also called a functor, functional, or functionoid, is a computer programming construct allowing an object to be invoked or called as though it were an ordinary function, usually with the same syntax.-Description:...

  • Job scheduler
    Job scheduler
    A job scheduler is a software application that is in charge of unattended background executions, commonly known for historical reasons as batch processing....

  • Model-view-controller
    Model-view-controller
    Model–view–controller is a software architecture, currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" from the user interface , permitting independent development, testing and maintenance of each .Model View Controller...

  • Priority queue
    Priority queue
    A priority queue is an abstract data type in computer programming.It is exactly like a regular queue or stack data structure, but additionally, each element is associated with a "priority"....


External links
  • http://c2.com/cgi/wiki?CommandPattern
  • http://www.javaworld.com/javaworld/javatips/jw-javatip68.html
  • PerfectJPattern Open Source Project, Provides a componentized i.e. context-free and type-safe implementation of the Command Pattern in Java
  • Command Pattern Video Tutorial , Teaches the Command Pattern using StarCraft references with a free downloadable video tutorial
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK