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.
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:
ThreadPool class could have a method addTask(Runnable task) that accepts any object that implements the interface.
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.
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.
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* = self.subject msg* = self.sender msg* = self.recipient s = smtplib.SMTP(self.server, self.port) s.sendmail(self.sender, *, 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.)
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); } };
Kommando (Entwurfsmuster) | Command (patrón de diseño) | Commande (motif de conception) | Command pattern | Wzorzec polecenia
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Command pattern".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world