Patternadvanced
Command Processor
Also called command processor pattern, command processor.
A command processor receives command objects, executes them and keeps them. Because all requests pass through it, it can add services such as undo, redo, logging and scheduling.
- Family
- behavioral-design
- Intent
- Separate the request for a service from its execution: a command processor component manages requests as separate objects, schedules their execution and provides services such as undo.
Intent
The Command Processor pattern "separates the request for a service from its execution".1
A command processor component manages requests as separate objects, schedules their execution, and provides additional services, for example it stores request objects for later undo.2
Problem
An application with many features needs a clear mapping from its interface to its internal functions. Users work in different ways: with pop-up menus, with keyboard shortcuts, or with a scripting language. The application also needs services that go beyond the core functions, such as undo, redo, macros, logging and scheduling of requests. These services must work in the same way for all requests, and new features must not break existing code.2
If each user interface element calls the functional core directly, each element must also do the work of each service. Here the menu records its requests for undo, but the keyboard shortcut does not, so undo removes the wrong word:
This code runs but gives a wrong answer on purpose.
class Insert:
def __init__(self, words, word):
self.words, self.word = words, word
def execute(self):
self.index = len(self.words)
self.words.append(self.word)
def undo(self):
del self.words[self.index]
words, history = [], []
def menu_insert(word):
command = Insert(words, word)
command.execute()
history.append(command)
def key_insert(word):
words.append(word) # calls the core directly, so undo does not know
menu_insert("hello")
key_insert("world")
print("text:", " ".join(words))
history.pop().undo() # meant to undo "world"
print("text:", " ".join(words))
text: hello world
text: world
Solution
Turn each request into a command object, and give all command objects to one command processor. The pattern builds on the Command pattern of Gamma, Helm, Johnson and Vlissides, and it shows in more detail how command objects are managed.2
Controller --creates--> Command --uses--> Supplier
| ^
| transfers | implements
v |
Command Processor ---> Abstract Command
do_it(command) execute()
undo_it() undo()
stack of commands
The participants work as follows:2
- The abstract command defines a uniform interface to execute commands. The services of the processor add other methods, for example
undo. - A command encapsulates one function request. It uses zero or more suppliers to do the work. For undo, a command saves the state of its suppliers before it executes, and it restores that state when it is undone.
- The controller is the interface of the application. It accepts requests, such as a request to paste text, and creates the corresponding command objects.
- The command processor activates the execution of commands and keeps them. It knows only the abstract command interface, so it stays independent of specific commands.
- A supplier gives most of the functionality that the commands need. In the editor example of the book, the supplier is the internal text representation.
Example
The example files show one program in each language. A document is a list of words. Insert is a command that adds a word, and it can undo itself. A Processor executes each command, prints a log line, and keeps the command on a stack. undo takes the last command from the stack and undoes it. The program prints:
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
class Insert:
def __init__(self, words, word):
self.words, self.word = words, word
def name(self):
return f"insert {self.word}"
def execute(self):
self.words.append(self.word)
def undo(self):
self.words.pop()
class Processor:
def __init__(self):
self.done = []
def do_it(self, command):
print(f"do: {command.name()}")
command.execute()
self.done.append(command)
def undo_it(self):
command = self.done.pop()
print(f"undo: {command.name()}")
command.undo()
words, processor = [], Processor()
processor.do_it(Insert(words, "hello"))
processor.do_it(Insert(words, "world"))
print("text:", " ".join(words))
processor.undo_it()
print("text:", " ".join(words))
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom. Any object with
name,executeandundomethods is a command, and the processor keeps a list of the commands that it executed.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Command {
virtual ~Command() = default;
virtual std::string name() const = 0;
virtual void execute() = 0;
virtual void undo() = 0;
};
class Insert : public Command {
public:
Insert(std::vector<std::string>& words, std::string word) : words_(words), word_(std::move(word)) {}
std::string name() const override { return "insert " + word_; }
void execute() override { words_.push_back(word_); }
void undo() override { words_.pop_back(); }
private:
std::vector<std::string>& words_;
std::string word_;
};
class Processor {
public:
void doIt(std::unique_ptr<Command> command) {
std::cout << "do: " << command->name() << "\n";
command->execute();
done_.push_back(std::move(command));
}
void undoIt() {
std::unique_ptr<Command> command = std::move(done_.back());
done_.pop_back();
std::cout << "undo: " << command->name() << "\n";
command->undo();
}
private:
std::vector<std::unique_ptr<Command>> done_;
};
std::string join(const std::vector<std::string>& words) {
std::string out;
for (const auto& w : words) out += (out.empty() ? "" : " ") + w;
return out;
}
int main() {
std::vector<std::string> words;
Processor processor;
processor.doIt(std::make_unique<Insert>(words, "hello"));
processor.doIt(std::make_unique<Insert>(words, "world"));
std::cout << "text: " << join(words) << "\n";
processor.undoIt();
std::cout << "text: " << join(words) << "\n";
}
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom.
Commandis an abstract class, and the processor owns the executed commands throughstd::unique_ptr.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
interface Command {
String name();
void execute();
void undo();
}
class Insert implements Command {
private final List<String> words;
private final String word;
Insert(List<String> words, String word) {
this.words = words;
this.word = word;
}
public String name() { return "insert " + word; }
public void execute() { words.add(word); }
public void undo() { words.remove(words.size() - 1); }
}
class Processor {
private final Deque<Command> done = new ArrayDeque<>();
void doIt(Command command) {
System.out.println("do: " + command.name());
command.execute();
done.push(command);
}
void undoIt() {
Command command = done.pop();
System.out.println("undo: " + command.name());
command.undo();
}
}
public class Main {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
Processor processor = new Processor();
processor.doIt(new Insert(words, "hello"));
processor.doIt(new Insert(words, "world"));
System.out.println("text: " + String.join(" ", words));
processor.undoIt();
System.out.println("text: " + String.join(" ", words));
}
}
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom.
Commandis an interface, and the processor keeps the executed commands in anArrayDequeused as a stack.
using System;
using System.Collections.Generic;
interface ICommand
{
string Name { get; }
void Execute();
void Undo();
}
class Insert : ICommand
{
private readonly List<string> words;
private readonly string word;
public Insert(List<string> words, string word)
{
this.words = words;
this.word = word;
}
public string Name => $"insert {word}";
public void Execute() => words.Add(word);
public void Undo() => words.RemoveAt(words.Count - 1);
}
class Processor
{
private readonly Stack<ICommand> done = new();
public void DoIt(ICommand command)
{
Console.WriteLine($"do: {command.Name}");
command.Execute();
done.Push(command);
}
public void UndoIt()
{
var command = done.Pop();
Console.WriteLine($"undo: {command.Name}");
command.Undo();
}
}
class Program
{
static void Main()
{
var words = new List<string>();
var processor = new Processor();
processor.DoIt(new Insert(words, "hello"));
processor.DoIt(new Insert(words, "world"));
Console.WriteLine("text: " + string.Join(" ", words));
processor.UndoIt();
Console.WriteLine("text: " + string.Join(" ", words));
}
}
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom.
ICommandis the abstract command, and the processor keeps executed commands in aStack<ICommand>.
class Insert {
constructor(words, word) {
this.words = words;
this.word = word;
}
name() {
return `insert ${this.word}`;
}
execute() {
this.words.push(this.word);
}
undo() {
this.words.pop();
}
}
class Processor {
constructor() {
this.done = [];
}
doIt(command) {
console.log(`do: ${command.name()}`);
command.execute();
this.done.push(command);
}
undoIt() {
const command = this.done.pop();
console.log(`undo: ${command.name()}`);
command.undo();
}
}
const words = [];
const processor = new Processor();
processor.doIt(new Insert(words, "hello"));
processor.doIt(new Insert(words, "world"));
console.log("text:", words.join(" "));
processor.undoIt();
console.log("text:", words.join(" "));
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom. A command is any object with
name,executeandundo, and the processor keeps an array of executed commands.
interface Command {
name(): string;
execute(): void;
undo(): void;
}
class Insert implements Command {
private words: string[];
private word: string;
constructor(words: string[], word: string) {
this.words = words;
this.word = word;
}
name(): string {
return `insert ${this.word}`;
}
execute(): void {
this.words.push(this.word);
}
undo(): void {
this.words.pop();
}
}
class Processor {
private done: Command[] = [];
doIt(command: Command): void {
console.log(`do: ${command.name()}`);
command.execute();
this.done.push(command);
}
undoIt(): void {
const command = this.done.pop();
if (command === undefined) return;
console.log(`undo: ${command.name()}`);
command.undo();
}
}
const words: string[] = [];
const processor = new Processor();
processor.doIt(new Insert(words, "hello"));
processor.doIt(new Insert(words, "world"));
console.log("text:", words.join(" "));
processor.undoIt();
console.log("text:", words.join(" "));
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom. The interface
Commandis the abstract command, and the processor knows only that interface.
package main
import (
"fmt"
"strings"
)
type Command interface {
Name() string
Execute()
Undo()
}
type Insert struct {
words *[]string
word string
}
func (c Insert) Name() string { return "insert " + c.word }
func (c Insert) Execute() { *c.words = append(*c.words, c.word) }
func (c Insert) Undo() { *c.words = (*c.words)[:len(*c.words)-1] }
type Processor struct {
done []Command
}
func (p *Processor) DoIt(c Command) {
fmt.Println("do:", c.Name())
c.Execute()
p.done = append(p.done, c)
}
func (p *Processor) UndoIt() {
c := p.done[len(p.done)-1]
p.done = p.done[:len(p.done)-1]
fmt.Println("undo:", c.Name())
c.Undo()
}
func main() {
var words []string
p := &Processor{}
p.DoIt(Insert{&words, "hello"})
p.DoIt(Insert{&words, "world"})
fmt.Println("text:", strings.Join(words, " "))
p.UndoIt()
fmt.Println("text:", strings.Join(words, " "))
}
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom.
Commandis an interface, and the processor keeps a slice of executed commands as a stack.
trait Command {
fn name(&self) -> String;
fn execute(&self, words: &mut Vec<String>);
fn undo(&self, words: &mut Vec<String>);
}
struct Insert(String);
impl Command for Insert {
fn name(&self) -> String {
format!("insert {}", self.0)
}
fn execute(&self, words: &mut Vec<String>) {
words.push(self.0.clone());
}
fn undo(&self, words: &mut Vec<String>) {
words.pop();
}
}
struct Processor {
words: Vec<String>, // the supplier
done: Vec<Box<dyn Command>>,
}
impl Processor {
fn do_it(&mut self, command: Box<dyn Command>) {
println!("do: {}", command.name());
command.execute(&mut self.words);
self.done.push(command);
}
fn undo_it(&mut self) {
if let Some(command) = self.done.pop() {
println!("undo: {}", command.name());
command.undo(&mut self.words);
}
}
}
fn main() {
let mut p = Processor { words: Vec::new(), done: Vec::new() };
p.do_it(Box::new(Insert("hello".to_string())));
p.do_it(Box::new(Insert("world".to_string())));
println!("text: {}", p.words.join(" "));
p.undo_it();
println!("text: {}", p.words.join(" "));
}
do: insert hello
do: insert world
text: hello world
undo: insert world
text: hello
- Verdict: idiom.
Commandis a trait, and the processor keepsBox<dyn Command>values. The commands get the supplier as a&mutparameter, so no command holds a mutable reference to it.
Consequences
The benefits:2
- Flexible activation. Different user interface elements can create the same kind of command object, so it is easy to remap user input, for example to an emacs or a WordStar keyboard.
- Flexible number of requests. A new command class does not change the controller or the command processor. Complex commands can be made from existing ones, for example as macros.
- Services in one place. A command processor can log commands, store them to a file for replay, queue them, schedule them by time or priority, or run them in a separate thread.
- Testability. The command processor is an entry point for tests, and a stored sequence of commands can be applied again after an error is corrected.
Here a macro is a command made of other commands. The processor undoes it as one step:
class Insert:
def __init__(self, words, word):
self.words, self.word = words, word
def execute(self):
self.words.append(self.word)
def undo(self):
self.words.pop()
class Macro:
def __init__(self, *commands):
self.commands = commands
def execute(self):
for command in self.commands:
command.execute()
def undo(self):
for command in reversed(self.commands):
command.undo()
class Processor:
def __init__(self):
self.done = []
def do_it(self, command):
command.execute()
self.done.append(command)
def undo_it(self):
self.done.pop().undo()
words, processor = [], Processor()
processor.do_it(Insert(words, "dear"))
processor.do_it(Macro(Insert(words, "best"), Insert(words, "regards")))
print("text:", " ".join(words))
processor.undo_it()
print("text:", " ".join(words))
text: dear best regards
text: dear
The liabilities:2
- Efficiency loss. The extra indirection costs storage and time.
- Many command classes. A rich application can have many command classes. Group them around abstractions, pass the supplier as a parameter to simple commands, or build macros from a few low-level commands.
- Command parameters. A command that asks the user for more parameters during its execution complicates event handling, because events must go both to the controller and to the active command.
- Concurrency. Commands that run in parallel threads need synchronization when they access shared data, for example in a supplier.
When not to use it
- The application has few requests and no services such as undo, logging or scheduling. A controller that performs each request directly has no efficiency penalty.2
- New requests, changes to services and an undo mechanism are not expected. These changes need more effort with a direct controller.2
Variants and related patterns
- Spread controller functionality. Several components share the role of the controller. For example, each menu button creates a command object when it is activated.2
- Combination with Interpreter. A scripting language gives a programmable interface. The parser takes the role of the controller and builds the abstract syntax tree from command objects. The command processor is the client of the Interpreter, and it activates the commands.2
- Command. In Command Processor, the controller takes the role of the client of the Command pattern, and the command processor takes the role of the invoker. The suppliers correspond to the receivers, but a command can use more than one supplier.2
Known uses
- The ET++ framework has command processors that support unlimited, bounded and single undo and redo. MacApp uses the pattern for undoable operations, and InterViews has an action class that is an abstract command.2
- Qt's
QUndoStackis a stack ofQUndoCommandobjects. New commands are pushed on the stack withpush(), and they are undone and redone withundo()andredo().3 - IDLE, the editor of Python, has an
UndoDelegator. Itsaddcmdmethod executes a command and adds it to an undo list, andundo_eventandredo_eventmove through that list.4
References
- Examples to Accompany: Design Patterns, Elements of Reusable Object-Oriented Software, AG Communication Systems, 1999, Command Processor, page A-47
- Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad and Michael Stal, Pattern-Oriented Software Architecture, Volume 1: A System of Patterns, John Wiley and Sons, Command Processor, pages 277 to 290 (Example, Context, Problem, Solution, Structure, Variants, Known Uses, Consequences, See Also, Credits)
- Qt v6.8.0 source, qtbase/src/gui/util/qundostack.cpp, class QUndoStack documentation, lines 310 to 324
- CPython v3.14.0 source, Lib/idlelib/undo.py, UndoDelegator.addcmd, undo_event and redo_event, lines 116 to 159
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 4PXDGG Edit this page History Report an error Markdown