|
In object-oriented programming, the Command pattern is a design pattern in which objects are used to represent actions. A command object encapsulates an action and its parameters. In computer science, object-oriented programming, OOP for short, is a computer programming paradigm. ...
{{Hide = {{{ Hybrid reference style allows grouped references at top, but uses m:Cite. ...
In computer science, the principle of information hiding is the hiding of design decisions in a computer program that are most likely to change, thus protecting other parts of the program from change if the design decision is changed. ...
For example, a printing library might include a PrintJob class. A user would typically create a new PrintJob object, set its properties (the document to be printed, the number of copies, and so on), and finally call a method to send the job to the printer. In this case, the same functionality could be exposed via a single SendJobToPrinter() procedure with many parameters. As it takes more code to write a command class than to write a procedure, there must be some reason to use a class. There are many possible reasons: - It can improve API design. In some cases, code that uses a command object is shorter, clearer, and more declarative than code that uses a procedure with many parameters. This is particularly true if a caller typically uses only a handful of the parameters and is willing to accept sensible defaults for the rest.
- A command object is convenient temporary storage for procedure parameters. It can be used while assembling the parameters for a function call and allows the command to be set aside for later use.
- A class is a convenient place to collect code and data related to a command. A command object can hold information about the command, such as its name or which user launched it; and answer questions about it, such as how long it will likely take.
- Treating commands as objects enables data structures containing multiple commands. A complex process could be treated as a tree or graph of command objects. A thread pool could maintain a priority queue of command objects consumed by worker threads.
- Treating commands as objects supports undo-able operations, provided that the command objects are stored (for example in a stack)
- The command is a useful abstraction for building generic components, such as a thread pool, that can handle command objects of any type. If a new type of command object is created later, it can work with these generic components automatically. For example, in Java, a generic
ThreadPool class could have a method addTask(Runnable task) that accepts any object that implements the java.lang.Runnable interface. A binary tree, a simple type of branching linked data structure. ...
In computer science, a tree is a widely-used computer data structure that emulates a tree structure with a set of linked nodes. ...
In the thread pool pattern in programming, a number of N threads are created to perform a number of M tasks, usually organized in a queue. ...
A priority queue is an ADT (abstract data type) supporting the following two operations: add an element to the queue with an associated priority remove the element from the queue that has the highest priority, and return it The simplest way to implement a priority queue data type is to...
A stack is a data structure that works on the principle of Last In First Out (LIFO). ...
Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1990s. ...
Uses for the Command pattern Command objects are useful for implementing: - Multi-level undo
- 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 behavior
- Undo is perhaps even more essential when it's called rollback and happens automatically when an operation fails partway through. Installers need this. So do databases. Command objects can also be used to implement two-phase commit.
- Progress bars
- 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.
- Wizards
- 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 programming, an
Action 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.
Undo is a command in most word processors and text editors. ...
A database transaction is a unit of interaction with a database management system or similar system that is treated in a coherent and reliable way independent of other transactions that must be either entirely completed or aborted. ...
An installation program or installer is a computer program that installs files, such as applications, drivers, or other software, onto a computer. ...
It has been suggested that this article or section be merged into Two-phase-commit protocol. ...
A generic example of a progress bar, along with a textual percentage representation. ...
A wizard is an interactive computer program acting as an interface to lead a user through a complex task using dialog steps. ...
Example Swing widgets Swing is a GUI toolkit for Java. ...
In the thread pool pattern in programming, a number of N threads are created to perform a number of M tasks, usually organized in a queue. ...
...
Examples This Python program defines a command class for sending a simple SMTP mail message. The test() function demonstrates how the command class can be used to send a message. Python is an interpreted programming language created by Guido van Rossum in 1990. ...
import email.MIMEText, smtplib class SendMailCommand: """ A simple command object for sending SMTP mail. """ def __init__(self): self.server = 'mail' self.port = smtplib.SMTP_PORT self.sender = None self.recipient = None self.subject = '' self.message = '' def execute(self): """ Send the message via SMTP. """ msg = email.MIMEText.MIMEText(self.message) msg['Subject'] = self.subject msg['From'] = self.sender msg['To'] = self.recipient s = smtplib.SMTP(self.server, self.port) s.sendmail(self.sender, [self.recipient], msg.as_string()) s.close() def test(): smc = SendMailCommand() smc.sender = 'harold@example.com' smc.recipient = 'maude@example.com' smc.subject = 'Design patterns' smc.message = file('dp.txt').read() smc.execute() The next example in Python defines a class, ThreadPool, for executing commands asynchronously. import threading, Queue class _WorkerThread(threading.Thread): def __init__(self, queue): self.queue = queue def run(self): while True: cmd = self.queue.get() cmd.execute() class ThreadPool: """ A simple thread pool for executing commands asynchronously. """ def __init__(self, N=4): self.queue = Queue.Queue() self.threads = [] for i in range(N): t = _WorkerThread(self.queue) t.start() self.threads.append(t) def addCommand(self, cmd): """ Add a command to the queue of tasks. The command will be executed in a worker thread. Commands are executed in first-come-first-served order. cmd - Any object with an .execute() method that accepts 0 arguments. """ self.queue.put(cmd) This generic thread pool works with any command object. It could be passed SendMailCommand objects, for example. Generic code that operates on command objects can be powerful and flexible while providing a simple API. (Note: For brevity, this example omits many features that a real-world thread pool should have, such as exception handling.) Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ...
Here is a C++ example: // Imaginary example of a command object used with a text editor class EditorCommandInterface { public: virtual void execute(TextEditor& target) = 0; }; class CutCommand : public EditorCommandInterface { public: virtual void execute(TextEditor& target) { string s = target.GetSelectedText(); target.DeleteRange(target.GetSelectStart(), target.GetSelectEnd()); Clipboard.Copy(s); } }; References - Freeman,E;Sierra,K;Bates,B (2004). Head First Design Patterns. O'Reilly.
See also In programming languages, a closure is a function that refers to free variables in its lexical context. ...
{{Hide = {{{ Hybrid reference style allows grouped references at top, but uses m:Cite. ...
External links |