English

Artykuł · Polecenie · CQRS

Polecenie (Command): żądanie zamknięte w obiekcie

Wzorzec Polecenie na przykładzie terminala kelnerskiego w pierogarni: każda akcja na bonie to obiekt z metodami execute i undo, więc da się ją cofnąć, ponowić, zapisać w historii i wysłać do kolejki. Kod w pięciu językach.

Autor · · 11 min czytania

Kelnerka w pierogarni Haliny dopisuje do bonu dwie porcje ruskich, kompot i rabat dla stałego klienta. Klient się rozmyśla – kompot ma zniknąć, ale ruskie zostają. Polecenie (ang. Command) zamienia każde kliknięcie w obiekt, który wie, jak się wykonać i jak się cofnąć. Dzięki temu cofanie, historia i kolejka do kuchni przestają być osobnymi problemami.

2
stosy wystarczą do undo/redo – wykonane i cofnięte polecenia
1
metoda, którą zna wywołujący – execute() – reszta jest w poleceniu
∞
sposobów użycia obiektu-żądania – kolejka, log, makro, ponowienie po awarii

Problem: przycisk, który robi wszystko sam

Terminal przy kasie zaczynał od jednego switcha obsługującego przyciski:

terminal-before.ts
class Terminal {
  constructor(private readonly ticket: Ticket) {}

  onButton(action: string, payload: any): void {
    switch (action) {
      case 'add':      this.ticket.lines.push(payload); break;
      case 'remove':   this.ticket.lines.splice(payload.index, 1); break;
      case 'discount': this.ticket.discount = payload.percent; break;
      // undo? "Just delete the ticket and start again." – the waitress
    }
  }
}

Logika akcji siedzi w obsłudze przycisków, więc nie da się jej użyć z innego miejsca – na przykład ze skrótu klawiszowego albo z aplikacji na telefon. Nie ma śladu tego, co zrobiono, więc nie ma cofania. Nie da się też odłożyć akcji na później: gdy drukarka w kuchni jest offline, zamówienie przepada, bo „akcja” istniała tylko jako wywołanie metody.

Rozwiązanie: każda akcja to obiekt

Każda operacja na bonie staje się klasą z metodą execute() (i opcjonalnie undo()). Obiekt polecenia trzyma referencję do odbiorcy (bonu) i wszystkie parametry. Terminal – wywołujący – tylko uruchamia polecenia i odkłada je na stos historii. Cofnięcie to zdjęcie polecenia ze stosu i wywołanie jego undo().

Diagram: Uruchamianie, cofanie i ponawianie poleceń
Diagram: Uczestnicy wzorca Polecenie
RolaW przykładzieOdpowiedzialność
Polecenie (Command)Commandinterfejs execute() / undo()
Konkretne polecenieAddDish, SetDiscountparametry żądania i wiedza, jak je wykonać i cofnąć
Odbiorca (Receiver)Ticketobiekt, na którym polecenie faktycznie działa
Wywołujący (Invoker)Terminaluruchamia polecenia, prowadzi historię
Klientobsługa przyciskutworzy polecenie i przekazuje je wywołującemu

Implementacja w pięciu językach

Każdy wariant ma ten sam scenariusz: dwie pozycje, rabat, dwa cofnięcia i jedno ponowienie. W TypeScripcie polecenia są zwykłymi obiektami tworzonymi przez funkcje, a etykieta label pokazuje, że polecenie to także dane – można wyświetlić historię albo wysłać ją przez sieć.

Polecenie – terminal kelnerski

Terminal.cs
var ticket = new Ticket();
var terminal = new Terminal();
terminal.Run(new AddDish(ticket, "Ruskie", 2));
terminal.Run(new AddDish(ticket, "Kompot", 1));
terminal.Run(new SetDiscount(ticket, 10));
terminal.Undo();           // discount removed
terminal.Undo();           // kompot removed
terminal.Redo();           // kompot is back
Console.WriteLine(ticket); // Ruskie x2, Kompot x1, discount 0%

public interface ICommand
{
    void Execute();
    void Undo();
}

public sealed class Ticket
{
    public List<(string Dish, int Qty)> Lines { get; } = [];
    public int DiscountPercent { get; set; }

    public override string ToString() =>
        $"{string.Join(", ", Lines.Select(l => $"{l.Dish} x{l.Qty}"))}, discount {DiscountPercent}%";
}

public sealed class AddDish(Ticket ticket, string dish, int qty) : ICommand
{
    public void Execute() => ticket.Lines.Add((dish, qty));
    public void Undo() => ticket.Lines.RemoveAt(ticket.Lines.Count - 1); // undo runs in LIFO order
}

public sealed class SetDiscount(Ticket ticket, int percent) : ICommand
{
    private int _previous; // what Undo needs to restore

    public void Execute() => (_previous, ticket.DiscountPercent) = (ticket.DiscountPercent, percent);
    public void Undo() => ticket.DiscountPercent = _previous;
}

public sealed class Terminal
{
    private readonly Stack<ICommand> _done = new();
    private readonly Stack<ICommand> _undone = new();

    public void Run(ICommand command)
    {
        command.Execute();
        _done.Push(command);
        _undone.Clear(); // a new action invalidates the redo history
    }

    public void Undo() { if (_done.TryPop(out var c)) { c.Undo(); _undone.Push(c); } }

    public void Redo() { if (_undone.TryPop(out var c)) { c.Execute(); _done.Push(c); } }
}
terminal.ts
interface Command {
  readonly label: string; // commands are data: they can be listed, logged, sent
  execute(): void;
  undo(): void;
}

class Ticket {
  lines: { dish: string; qty: number }[] = [];
  discountPercent = 0;
}

const addDish = (ticket: Ticket, dish: string, qty: number): Command => ({
  label: `add ${dish} x${qty}`,
  execute: () => void ticket.lines.push({ dish, qty }),
  undo: () => void ticket.lines.pop(), // undo runs in LIFO order
});

const setDiscount = (ticket: Ticket, percent: number): Command => {
  let previous = 0;
  return {
    label: `discount ${percent}%`,
    execute: () => { previous = ticket.discountPercent; ticket.discountPercent = percent; },
    undo: () => { ticket.discountPercent = previous; },
  };
};

class Terminal {
  private done: Command[] = [];
  private undone: Command[] = [];

  run(command: Command): void {
    command.execute();
    this.done.push(command);
    this.undone = []; // a new action invalidates the redo history
  }

  undo(): void {
    const command = this.done.pop();
    if (command) { command.undo(); this.undone.push(command); }
  }

  redo(): void {
    const command = this.undone.pop();
    if (command) { command.execute(); this.done.push(command); }
  }

  get history(): string[] { return this.done.map((c) => c.label); }
}

const ticket = new Ticket();
const terminal = new Terminal();
terminal.run(addDish(ticket, 'Ruskie', 2));
terminal.run(addDish(ticket, 'Kompot', 1));
terminal.run(setDiscount(ticket, 10));
terminal.undo();
console.log(terminal.history); // ['add Ruskie x2', 'add Kompot x1']
Terminal.java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

interface Command {
    void execute();
    void undo();
}

class Ticket {
    final List<String> lines = new ArrayList<>();
    int discountPercent;

    @Override public String toString() { return lines + ", discount " + discountPercent + "%"; }
}

record AddDish(Ticket ticket, String dish, int qty) implements Command {
    public void execute() { ticket.lines.add(dish + " x" + qty); }
    public void undo() { ticket.lines.removeLast(); } // undo runs in LIFO order (Java 21+)
}

final class SetDiscount implements Command {
    private final Ticket ticket;
    private final int percent;
    private int previous; // what undo needs to restore

    SetDiscount(Ticket ticket, int percent) { this.ticket = ticket; this.percent = percent; }

    public void execute() { previous = ticket.discountPercent; ticket.discountPercent = percent; }
    public void undo() { ticket.discountPercent = previous; }
}

public class Terminal {
    private final Deque<Command> done = new ArrayDeque<>();
    private final Deque<Command> undone = new ArrayDeque<>();

    public void run(Command command) {
        command.execute();
        done.push(command);
        undone.clear(); // a new action invalidates the redo history
    }

    public void undo() { var c = done.poll(); if (c != null) { c.undo(); undone.push(c); } }

    public void redo() { var c = undone.poll(); if (c != null) { c.execute(); done.push(c); } }

    public static void main(String[] args) {
        var ticket = new Ticket();
        var terminal = new Terminal();
        terminal.run(new AddDish(ticket, "Ruskie", 2));
        terminal.run(new AddDish(ticket, "Kompot", 1));
        terminal.run(new SetDiscount(ticket, 10));
        terminal.undo();
        terminal.undo();
        terminal.redo();
        System.out.println(ticket); // [Ruskie x2, Kompot x1], discount 0%
    }
}
terminal.go
package main

import "fmt"

type Command interface {
	Execute()
	Undo()
}

type Ticket struct {
	Lines           []string
	DiscountPercent int
}

type AddDish struct {
	T    *Ticket
	Dish string
	Qty  int
}

func (c AddDish) Execute() { c.T.Lines = append(c.T.Lines, fmt.Sprintf("%s x%d", c.Dish, c.Qty)) }
func (c AddDish) Undo()    { c.T.Lines = c.T.Lines[:len(c.T.Lines)-1] } // undo runs in LIFO order

type SetDiscount struct {
	T        *Ticket
	Percent  int
	previous int // what Undo needs to restore
}

func (c *SetDiscount) Execute() { c.previous, c.T.DiscountPercent = c.T.DiscountPercent, c.Percent }
func (c *SetDiscount) Undo()    { c.T.DiscountPercent = c.previous }

type Terminal struct{ done, undone []Command }

func (t *Terminal) Run(c Command) {
	c.Execute()
	t.done = append(t.done, c)
	t.undone = nil // a new action invalidates the redo history
}

func move(from, to *[]Command, act func(Command)) {
	if len(*from) == 0 {
		return
	}
	c := (*from)[len(*from)-1]
	*from = (*from)[:len(*from)-1]
	act(c)
	*to = append(*to, c)
}

func (t *Terminal) Undo() { move(&t.done, &t.undone, Command.Undo) }
func (t *Terminal) Redo() { move(&t.undone, &t.done, Command.Execute) }

func main() {
	ticket := &Ticket{}
	var term Terminal
	term.Run(AddDish{ticket, "Ruskie", 2})
	term.Run(AddDish{ticket, "Kompot", 1})
	term.Run(&SetDiscount{T: ticket, Percent: 10})
	term.Undo()
	term.Undo()
	term.Redo()
	fmt.Println(ticket.Lines, ticket.DiscountPercent) // [Ruskie x2 Kompot x1] 0
}
terminal.py
from dataclasses import dataclass, field
from typing import Protocol


class Command(Protocol):
    def execute(self) -> None: ...
    def undo(self) -> None: ...


@dataclass
class Ticket:
    lines: list[str] = field(default_factory=list)
    discount_percent: int = 0


@dataclass
class AddDish:
    ticket: Ticket
    dish: str
    qty: int

    def execute(self) -> None:
        self.ticket.lines.append(f"{self.dish} x{self.qty}")

    def undo(self) -> None:
        self.ticket.lines.pop()  # undo runs in LIFO order


@dataclass
class SetDiscount:
    ticket: Ticket
    percent: int
    _previous: int = field(default=0, init=False, repr=False)  # what undo needs to restore

    def execute(self) -> None:
        self._previous, self.ticket.discount_percent = self.ticket.discount_percent, self.percent

    def undo(self) -> None:
        self.ticket.discount_percent = self._previous


class Terminal:
    def __init__(self) -> None:
        self._done: list[Command] = []
        self._undone: list[Command] = []

    def run(self, command: Command) -> None:
        command.execute()
        self._done.append(command)
        self._undone.clear()  # a new action invalidates the redo history

    def undo(self) -> None:
        if self._done:
            command = self._done.pop()
            command.undo()
            self._undone.append(command)

    def redo(self) -> None:
        if self._undone:
            command = self._undone.pop()
            command.execute()
            self._done.append(command)


ticket, terminal = Ticket(), Terminal()
terminal.run(AddDish(ticket, "Ruskie", 2))
terminal.run(AddDish(ticket, "Kompot", 1))
terminal.run(SetDiscount(ticket, 10))
terminal.undo()
terminal.undo()
terminal.redo()
print(ticket)  # Ticket(lines=['Ruskie x2', 'Kompot x1'], discount_percent=0)

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Dwa sposoby na cofanie
  • Operacja odwrotna
  • Migawka stanu
  • Polecenie jako dane: kolejki i ponowienia
  • Kiedy stosować, a kiedy nie
  • Polecenie a komenda w CQRS
  • Powiązania z innymi wzorcami
  • W praktyce
  • Sprawdź się

Załóż darmowe konto · Zaloguj się