Design Patterns

Pattern 14 sur 23, famille Comportement

Command

En français : Commande

Transformer une requête en objet autonome : on peut alors la passer en paramètre, la mettre en file, la journaliser ou l'annuler.

Le problème

Un éditeur a des boutons, raccourcis et menus qui déclenchent les mêmes actions. Il faut aussi un undo/redo. Mettre la logique dans chaque bouton duplique le code et rend l'annulation impossible.

La solution

Encapsuler chaque action dans un objet Command avec execute() et undo(). Un invoker (historique) exécute les commandes et les empile.

Le pattern en action

  • Client
  • Rôle clé du pattern
  • Objet
  • Données ou état
  1. Le clic crée un objet commande qui embarque son destinataire.
  2. L'invoker reçoit la commande, sans savoir ce qu'elle fait.
  3. History [ ] → WriteCommand : execute()
  4. La commande agit sur le receiver.
  5. La commande est empilée dans l'historique.
  6. L'utilisateur annule.
  7. History [WriteCommand] → WriteCommand : pop().undo()
  8. L'état précédent est restauré.

Une analogie

Au restaurant, le serveur note ta commande sur un ticket : le ticket peut être mis en file, transmis au chef, ou annulé.

Quand l'utiliser

  • Undo / redo, historique d'actions
  • Files de jobs, tâches différées (queues)
  • Macros, transactions, CQRS

Avantages et limites

Avantages

  • Découple l'émetteur de l'exécutant
  • Undo/redo et journalisation faciles
  • Composition de commandes (macros)

Limites

  • Beaucoup de petites classes
  • Undo complexe si l'état n'est pas réversible facilement

Implémentations

Le même exemple, écrit de façon idiomatique dans chaque langage.

Command en Python

command.py 44 lignes
from abc import ABC, abstractmethod


class Editor:
    def __init__(self):
        self.text = ""


class Command(ABC):
    @abstractmethod
    def execute(self) -> None: ...
    @abstractmethod
    def undo(self) -> None: ...


class Write(Command):
    def __init__(self, editor: Editor, s: str):
        self.editor, self.s = editor, s

    def execute(self):
        self.editor.text += self.s

    def undo(self):
        self.editor.text = self.editor.text[: -len(self.s)]


class History:
    def __init__(self):
        self._stack: list[Command] = []

    def run(self, cmd: Command):
        cmd.execute()
        self._stack.append(cmd)

    def undo(self):
        if self._stack:
            self._stack.pop().undo()


ed, h = Editor(), History()
h.run(Write(ed, "Hello "))
h.run(Write(ed, "World"))
h.undo()
print(ed.text)   # "Hello "

Command en TypeScript

command.ts 24 lignes
interface Command {
  execute(): void;
  undo(): void;
}

class Editor { text = ""; }

class WriteCommand implements Command {
  constructor(private editor: Editor, private s: string) {}
  execute() { this.editor.text += this.s; }
  undo() { this.editor.text = this.editor.text.slice(0, -this.s.length); }
}

class History {
  private stack: Command[] = [];
  run(c: Command) { c.execute(); this.stack.push(c); }
  undo() { this.stack.pop()?.undo(); }
}

const ed = new Editor();
const h = new History();
h.run(new WriteCommand(ed, "Hello "));
h.run(new WriteCommand(ed, "World"));
h.undo(); // ed.text === "Hello "

Command en Java

command.java 19 lignes
interface Command {
    void execute();
    void undo();
}

class Editor { final StringBuilder text = new StringBuilder(); }

record WriteCommand(Editor editor, String s) implements Command {
    public void execute() { editor.text.append(s); }
    public void undo() { editor.text.setLength(editor.text.length() - s.length()); }
}

class History {
    private final Deque<Command> stack = new ArrayDeque<>();

    void run(Command c) { c.execute(); stack.push(c); }

    void undo() { if (!stack.isEmpty()) stack.pop().undo(); }
}

Command en C#

command.cs 22 lignes
interface ICommand
{
    void Execute();
    void Undo();
}

class Editor { public string Text { get; set; } = ""; }

class WriteCommand(Editor editor, string s) : ICommand
{
    public void Execute() => editor.Text += s;
    public void Undo() => editor.Text = editor.Text[..^s.Length];
}

class History
{
    private readonly Stack<ICommand> _stack = new();

    public void Run(ICommand c) { c.Execute(); _stack.Push(c); }

    public void Undo() { if (_stack.TryPop(out var c)) c.Undo(); }
}

Command en PHP

command.php 30 lignes
interface Command
{
    public function execute(): void;
    public function undo(): void;
}

final class Editor { public string $text = ''; }

final class WriteCommand implements Command
{
    public function __construct(private Editor $editor, private string $s) {}

    public function execute(): void { $this->editor->text .= $this->s; }

    public function undo(): void
    {
        $this->editor->text = substr($this->editor->text, 0, -strlen($this->s));
    }
}

final class History
{
    private array $stack = [];

    public function run(Command $c): void { $c->execute(); $this->stack[] = $c; }

    public function undo(): void { array_pop($this->stack)?->undo(); }
}

// Les Jobs Laravel (dispatch(new SendInvoice($order))) sont des commandes mises en file

Command en Go

command.go 28 lignes
type Command interface {
    Execute()
    Undo()
}

type Editor struct{ Text string }

type WriteCommand struct {
    ed *Editor
    s  string
}

func (c WriteCommand) Execute() { c.ed.Text += c.s }
func (c WriteCommand) Undo()    { c.ed.Text = c.ed.Text[:len(c.ed.Text)-len(c.s)] }

type History struct{ stack []Command }

func (h *History) Run(c Command) {
    c.Execute()
    h.stack = append(h.stack, c)
}

func (h *History) Undo() {
    if n := len(h.stack); n > 0 {
        h.stack[n-1].Undo()
        h.stack = h.stack[:n-1]
    }
}

Questions fréquentes

Qu'est-ce que le design pattern Command ?

Transformer une requête en objet autonome : on peut alors la passer en paramètre, la mettre en file, la journaliser ou l'annuler. Encapsuler chaque action dans un objet Command avec execute() et undo(). Un invoker (historique) exécute les commandes et les empile.

Quand utiliser le pattern Command ?

Undo / redo, historique d'actions ; Files de jobs, tâches différées (queues) ; Macros, transactions, CQRS.

Quels sont les avantages et les inconvénients du pattern Command ?

Avantages : Découple l'émetteur de l'exécutant ; Undo/redo et journalisation faciles ; Composition de commandes (macros). Limites : Beaucoup de petites classes ; Undo complexe si l'état n'est pas réversible facilement.