Look-Alikes: Strategy, State and Command

Strategy, State and Command have the same class diagram: a promise, a few classes that keep it, and an object that holds one; what tells them apart is who picks the object, whether it changes itself, and whether it can be stored and undone, and picking the wrong one puts a decision in the wrong place.

Journeyman · OOP · Updated

By

After this lesson you can

  • Tell Strategy, State and Command apart by who picks the object, whether it changes itself, and whether it can be stored and undone
  • Choose between Strategy, State and Command for a new requirement, and say why

Key takeaways

  • On paper, Strategy, State and Command look the same: a promise, some classes that keep it, and something that holds one.
  • Strategy: the caller picks one way of doing a job, from outside, and it stays until the caller swaps it.
  • State: the object's current state answers for it, and each state picks the next one itself.
  • Command: each action is its own object, made when it's asked for, so it can be stored, logged, run later and undone.

Before this: Strategy: When the Rule Needs a Class of Its Own, State: What You Can Do Depends on Where It Is, and Command: An Action You Can Hold.

Priya has joined Lakeside Parcel's tracker team. On her first morning she reads three corners of the code: the carriers' rates, the package statuses and the dispatcher's actions. "These are all the same thing," she says. "An interface, a couple of classes that keep it, and an object that holds one. Why do they have three different names?" It's a fair question, and her first ticket shows why the answer matters: "Add a new status, held at the depot." Which of the three should it look like? This lesson puts the three side by side.

Three corners of the tracker, side by side

Here are all three, cut down to their shape from the Strategy, State and Command lessons. Each has a promise (an interface, or a base class whose methods the others fill in), two classes that keep it, and something that holds one:

// Strategy: the caller picks the carrier, from outside.
Console.WriteLine(Quote(new QuickShip(500, 200), 2));
Console.WriteLine(Quote(new SameDay(1500), 2));

// State: the package holds its status, and each status picks the next one.
Package parcel = new Package(42);
Console.WriteLine(parcel.Ship());
Console.WriteLine(parcel.Ship());

// Command: each action is an object, kept so it can be undone.
DispatchBoard board = new DispatchBoard();
AssignPackage assign = new AssignPackage(board, 42, "Dana");
assign.Execute();
Console.WriteLine(assign.Describe());
assign.Undo();
Console.WriteLine("Undo: " + assign.Describe());

string Quote(ICarrier carrier, int zone) => quot;{carrier.Name} to zone {zone}: {Dollars(carrier.Rate(zone))}";
string Dollars(int cents) => quot;${cents / 100}.{cents % 100:D2}";

interface ICarrier { string Name { get; } int Rate(int zone); }

class QuickShip : ICarrier
{
    private readonly int baseCents, perZoneCents;
    public QuickShip(int baseCents, int perZoneCents) { this.baseCents = baseCents; this.perZoneCents = perZoneCents; }
    public string Name => "QuickShip";
    public int Rate(int zone) => baseCents + perZoneCents * zone;
}

class SameDay : ICarrier
{
    private readonly int flatCents;
    public SameDay(int flatCents) { this.flatCents = flatCents; }
    public string Name => "SameDay";
    public int Rate(int zone) => flatCents;
}

abstract class PackageStatus
{
    public abstract string Name { get; }
    public virtual PackageStatus? Ship() => null; // null means "not from here"
}

class Ordered : PackageStatus
{
    public override string Name => "ordered";
    public override PackageStatus? Ship() => new Shipped();
}

class Shipped : PackageStatus
{
    public override string Name => "shipped";
}

class Package
{
    private PackageStatus status = new Ordered();
    private readonly int id;
    public Package(int id) { this.id = id; }

    public string Ship()
    {
        PackageStatus? next = status.Ship();
        if (next == null) { return quot;Package {id}: can't ship, it's {status.Name}"; }
        status = next;
        return quot;Package {id}: {status.Name}";
    }
}

interface IDispatchCommand { void Execute(); void Undo(); string Describe(); }

class AssignPackage : IDispatchCommand
{
    private readonly DispatchBoard board;
    private readonly int package;
    private readonly string driver;
    private string? driverBefore;

    public AssignPackage(DispatchBoard board, int package, string driver) { this.board = board; this.package = package; this.driver = driver; }
    public void Execute() { driverBefore = board.DriverFor(package); board.Assign(package, driver); }
    public void Undo() { if (driverBefore == null) { board.Unassign(package); } else { board.Assign(package, driverBefore); } }
    public string Describe() => quot;Assign package {package} to {driver}";
}

class DispatchBoard
{
    private readonly Dictionary<int, string> drivers = new Dictionary<int, string>();
    public string? DriverFor(int package) => drivers.TryGetValue(package, out string? driver) ? driver : null;
    public void Assign(int package, string driver) => drivers[package] = driver;
    public void Unassign(int package) => drivers.Remove(package);
}
QuickShip to zone 2: $9.00
SameDay to zone 2: $15.00
Package 42: shipped
Package 42: can't ship, it's shipped
Assign package 42 to Dana
Undo: Assign package 42 to Dana
// Strategy: the caller picks the carrier, from outside.
interface Carrier { String name(); int rate(int zone); }

class QuickShip implements Carrier {
    private final int baseCents, perZoneCents;
    QuickShip(int baseCents, int perZoneCents) { this.baseCents = baseCents; this.perZoneCents = perZoneCents; }
    public String name() { return "QuickShip"; }
    public int rate(int zone) { return baseCents + perZoneCents * zone; }
}

class SameDay implements Carrier {
    private final int flatCents;
    SameDay(int flatCents) { this.flatCents = flatCents; }
    public String name() { return "SameDay"; }
    public int rate(int zone) { return flatCents; }
}

String dollars(int cents) { return "quot; + cents / 100 + "." + String.format("%02d", cents % 100); }

String quote(Carrier carrier, int zone) { return carrier.name() + " to zone " + zone + ": " + dollars(carrier.rate(zone)); }

// State: the package holds its status, and each status picks the next one.
abstract class PackageStatus {
    abstract String name();
    PackageStatus ship() { return null; } // null means "not from here"
}

class Ordered extends PackageStatus {
    String name() { return "ordered"; }
    PackageStatus ship() { return new Shipped(); }
}

class Shipped extends PackageStatus {
    String name() { return "shipped"; }
}

class Package {
    private PackageStatus status = new Ordered();
    private final int id;
    Package(int id) { this.id = id; }

    String ship() {
        PackageStatus next = status.ship();
        if (next == null) { return "Package " + id + ": can't ship, it's " + status.name(); }
        status = next;
        return "Package " + id + ": " + status.name();
    }
}

// Command: each action is an object, kept so it can be undone.
interface DispatchCommand { void execute(); void undo(); String describe(); }

class DispatchBoard {
    private final Map<Integer, String> drivers = new HashMap<>();
    String driverFor(int pkg) { return drivers.get(pkg); }
    void assign(int pkg, String driver) { drivers.put(pkg, driver); }
    void unassign(int pkg) { drivers.remove(pkg); }
}

class AssignPackage implements DispatchCommand {
    private final DispatchBoard board;
    private final int pkg;
    private final String driver;
    private String driverBefore = null;

    AssignPackage(DispatchBoard board, int pkg, String driver) { this.board = board; this.pkg = pkg; this.driver = driver; }
    public void execute() { driverBefore = board.driverFor(pkg); board.assign(pkg, driver); }
    public void undo() { if (driverBefore == null) { board.unassign(pkg); } else { board.assign(pkg, driverBefore); } }
    public String describe() { return "Assign package " + pkg + " to " + driver; }
}

void main() {
    IO.println(quote(new QuickShip(500, 200), 2));
    IO.println(quote(new SameDay(1500), 2));

    Package parcel = new Package(42);
    IO.println(parcel.ship());
    IO.println(parcel.ship());

    DispatchBoard board = new DispatchBoard();
    AssignPackage assign = new AssignPackage(board, 42, "Dana");
    assign.execute();
    IO.println(assign.describe());
    assign.undo();
    IO.println("Undo: " + assign.describe());
}
QuickShip to zone 2: $9.00
SameDay to zone 2: $15.00
Package 42: shipped
Package 42: can't ship, it's shipped
Assign package 42 to Dana
Undo: Assign package 42 to Dana
# Strategy: the caller picks the carrier, from outside.
class QuickShip:
    name = "QuickShip"

    def __init__(self, base_cents, per_zone_cents):
        self.base_cents = base_cents
        self.per_zone_cents = per_zone_cents

    def rate(self, zone):
        return self.base_cents + self.per_zone_cents * zone


class SameDay:
    name = "SameDay"

    def __init__(self, flat_cents):
        self.flat_cents = flat_cents

    def rate(self, zone):
        return self.flat_cents


def dollars(cents):
    return f"${cents // 100}.{cents % 100:02d}"


def quote(carrier, zone):
    return f"{carrier.name} to zone {zone}: {dollars(carrier.rate(zone))}"


# State: the package holds its status, and each status picks the next one.
class PackageStatus:
    name = ""

    def ship(self):
        return None  # None means "not from here"


class Ordered(PackageStatus):
    name = "ordered"

    def ship(self):
        return Shipped()


class Shipped(PackageStatus):
    name = "shipped"


class Package:
    def __init__(self, package_id):
        self.package_id = package_id
        self.status = Ordered()

    def ship(self):
        next_status = self.status.ship()
        if next_status is None:
            return f"Package {self.package_id}: can't ship, it's {self.status.name}"
        self.status = next_status
        return f"Package {self.package_id}: {self.status.name}"


# Command: each action is an object, kept so it can be undone.
class DispatchBoard:
    def __init__(self):
        self.drivers = {}

    def driver_for(self, package):
        return self.drivers.get(package)

    def assign(self, package, driver):
        self.drivers[package] = driver

    def unassign(self, package):
        del self.drivers[package]


class AssignPackage:
    def __init__(self, board, package, driver):
        self.board = board
        self.package = package
        self.driver = driver
        self.driver_before = None

    def execute(self):
        self.driver_before = self.board.driver_for(self.package)
        self.board.assign(self.package, self.driver)

    def undo(self):
        if self.driver_before is None:
            self.board.unassign(self.package)
        else:
            self.board.assign(self.package, self.driver_before)

    def describe(self):
        return f"Assign package {self.package} to {self.driver}"


print(quote(QuickShip(500, 200), 2))
print(quote(SameDay(1500), 2))

parcel = Package(42)
print(parcel.ship())
print(parcel.ship())

board = DispatchBoard()
assign = AssignPackage(board, 42, "Dana")
assign.execute()
print(assign.describe())
assign.undo()
print("Undo: " + assign.describe())
QuickShip to zone 2: $9.00
SameDay to zone 2: $15.00
Package 42: shipped
Package 42: can't ship, it's shipped
Assign package 42 to Dana
Undo: Assign package 42 to Dana
// Strategy: the caller picks the carrier, from outside.
class QuickShip {
  name = "QuickShip";
  constructor(baseCents, perZoneCents) { this.baseCents = baseCents; this.perZoneCents = perZoneCents; }
  rate(zone) { return this.baseCents + this.perZoneCents * zone; }
}

class SameDay {
  name = "SameDay";
  constructor(flatCents) { this.flatCents = flatCents; }
  rate(zone) { return this.flatCents; }
}

function dollars(cents) {
  return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}

function quote(carrier, zone) { return `${carrier.name} to zone ${zone}: ${dollars(carrier.rate(zone))}`; }

// State: the package holds its status, and each status picks the next one.
class PackageStatus {
  name = "";
  ship() { return null; } // null means "not from here"
}

class Ordered extends PackageStatus {
  name = "ordered";
  ship() { return new Shipped(); }
}

class Shipped extends PackageStatus {
  name = "shipped";
}

class Package {
  #status = new Ordered();
  constructor(id) { this.id = id; }
  ship() {
    const next = this.#status.ship();
    if (next === null) { return `Package ${this.id}: can't ship, it's ${this.#status.name}`; }
    this.#status = next;
    return `Package ${this.id}: ${this.#status.name}`;
  }
}

// Command: each action is an object, kept so it can be undone.
class DispatchBoard {
  #drivers = new Map();
  driverFor(pkg) { return this.#drivers.get(pkg) ?? null; }
  assign(pkg, driver) { this.#drivers.set(pkg, driver); }
  unassign(pkg) { this.#drivers.delete(pkg); }
}

class AssignPackage {
  #driverBefore = null;
  constructor(board, pkg, driver) { this.board = board; this.pkg = pkg; this.driver = driver; }
  execute() { this.#driverBefore = this.board.driverFor(this.pkg); this.board.assign(this.pkg, this.driver); }
  undo() { if (this.#driverBefore === null) { this.board.unassign(this.pkg); } else { this.board.assign(this.pkg, this.#driverBefore); } }
  describe() { return `Assign package ${this.pkg} to ${this.driver}`; }
}

console.log(quote(new QuickShip(500, 200), 2));
console.log(quote(new SameDay(1500), 2));

const parcel = new Package(42);
console.log(parcel.ship());
console.log(parcel.ship());

const board = new DispatchBoard();
const assign = new AssignPackage(board, 42, "Dana");
assign.execute();
console.log(assign.describe());
assign.undo();
console.log("Undo: " + assign.describe());
QuickShip to zone 2: $9.00
SameDay to zone 2: $15.00
Package 42: shipped
Package 42: can't ship, it's shipped
Assign package 42 to Dana
Undo: Assign package 42 to Dana
// Strategy: the caller picks the carrier, from outside.
interface Carrier { name: string; rate(zone: number): number; }

class QuickShip implements Carrier {
  name = "QuickShip";
  baseCents: number;
  perZoneCents: number;
  constructor(baseCents: number, perZoneCents: number) { this.baseCents = baseCents; this.perZoneCents = perZoneCents; }
  rate(zone: number): number { return this.baseCents + this.perZoneCents * zone; }
}

class SameDay implements Carrier {
  name = "SameDay";
  flatCents: number;
  constructor(flatCents: number) { this.flatCents = flatCents; }
  rate(zone: number): number { return this.flatCents; }
}

function dollars(cents: number): string {
  return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}

function quote(carrier: Carrier, zone: number): string { return `${carrier.name} to zone ${zone}: ${dollars(carrier.rate(zone))}`; }

// State: the package holds its status, and each status picks the next one.
class PackageStatus {
  name = "";
  ship(): PackageStatus | null { return null; } // null means "not from here"
}

class Ordered extends PackageStatus {
  name = "ordered";
  ship(): PackageStatus | null { return new Shipped(); }
}

class Shipped extends PackageStatus {
  name = "shipped";
}

class Package {
  id: number;
  #status: PackageStatus = new Ordered();
  constructor(id: number) { this.id = id; }
  ship(): string {
    const next = this.#status.ship();
    if (next === null) { return `Package ${this.id}: can't ship, it's ${this.#status.name}`; }
    this.#status = next;
    return `Package ${this.id}: ${this.#status.name}`;
  }
}

// Command: each action is an object, kept so it can be undone.
interface DispatchCommand { execute(): void; undo(): void; describe(): string; }

class DispatchBoard {
  #drivers = new Map<number, string>();
  driverFor(pkg: number): string | null { return this.#drivers.get(pkg) ?? null; }
  assign(pkg: number, driver: string): void { this.#drivers.set(pkg, driver); }
  unassign(pkg: number): void { this.#drivers.delete(pkg); }
}

class AssignPackage implements DispatchCommand {
  board: DispatchBoard;
  pkg: number;
  driver: string;
  #driverBefore: string | null = null;
  constructor(board: DispatchBoard, pkg: number, driver: string) { this.board = board; this.pkg = pkg; this.driver = driver; }
  execute(): void { this.#driverBefore = this.board.driverFor(this.pkg); this.board.assign(this.pkg, this.driver); }
  undo(): void { if (this.#driverBefore === null) { this.board.unassign(this.pkg); } else { this.board.assign(this.pkg, this.#driverBefore); } }
  describe(): string { return `Assign package ${this.pkg} to ${this.driver}`; }
}

console.log(quote(new QuickShip(500, 200), 2));
console.log(quote(new SameDay(1500), 2));

const parcel = new Package(42);
console.log(parcel.ship());
console.log(parcel.ship());

const board = new DispatchBoard();
const assign = new AssignPackage(board, 42, "Dana");
assign.execute();
console.log(assign.describe());
assign.undo();
console.log("Undo: " + assign.describe());
QuickShip to zone 2: $9.00
SameDay to zone 2: $15.00
Package 42: shipped
Package 42: can't ship, it's shipped
Assign package 42 to Dana
Undo: Assign package 42 to Dana

QuickShip charges $5 plus $2 a zone, so zone 2 is $9.00; SameDay is $15.00 flat. Package 42 ships, and when it's asked to ship again, its Shipped status refuses. Dana gets package 42, and the assignment is taken back.

The same on paper

Draw the three as class diagrams and Priya is right: they're the same picture. A box that uses one of something; a promise; two classes that keep it. Only the names differ.

Strategy, State and Command draw the same class diagram: a holder uses a promise that two classes keep. Only their jobs differ: in Strategy the caller picks the carrier; in State each status picks the next; in Command each action is an object, stored, run later and undone

The diagram shows the parts; it doesn't show what they're for. Three questions do:

  1. Who picks the object? A strategy is picked by the caller, from outside: the shipping screen hands quote the carrier the customer chose. A state is picked by the state before it, from inside: Ordered decides that shipping leads to Shipped, and nobody outside does. A command is made by whoever asks for the action, one new object each time.
  2. Does it change itself? A strategy stays the same until the caller swaps it; QuickShip never turns into SameDay on its own. A state replaces itself as things happen; that's its whole job. A command doesn't change into another command; it's done, then kept.
  3. Can it be stored and undone? That's a command's job: each one is a record of something that happened, with what's needed to take it back. A strategy is a way of doing a job, and a state is where something is now; neither is a thing that happened.

Strategy, State or Command?

Pattern What it's for Strengths Weaknesses Pick it when
Strategy One way of doing a job, picked from outside and swapped as a whole A new way (a new carrier) is a new class; the code that uses it never changes The caller has to know which one to pick; one class per way There are several ways of doing the same job, and the caller or a setting chooses
State What an object can do right now, decided by where it is in its life The rules for each stage live in one class; the switch on status is gone; new states plug in The rules for moving between states are spread across the state classes What's allowed depends on a status that changes as things happen (draw its state diagram first)
Command One action as an object, so it can be stored, queued, logged, run later and undone A new action is a new class; history, plans and undo come almost free A class (or a pair of functions) per action, and every undo must be right Actions must be held: put in a plan, written to a log, retried, or undone

Priya's ticket

"Add a new status, held at the depot: a shipped package can be held, and a held package can be released to go out for delivery." Here's what each choice would do:

  • As a strategy (a status the caller picks): every screen that changes a package would have to know when a package may be held and when it may be released. The rules would be copied into the callers, which is the switch the State lesson removed.
  • As a command (a "hold" action): useful, and maybe wanted too, if the dispatcher needs to undo a hold. But a command doesn't say what a held package can do; something still has to refuse "cancel" for a held package.
  • As a state: one new class, HeldAtDepot, that says what a held package can do and which state comes next. Shipped learns one new arrow ("hold"). Nothing else changes.

It's a state: what the package can do depends on where it is. And notice the "maybe too": patterns combine. The dispatcher's "hold" button can be a command whose Execute asks the package to move to its next state, and whose Undo moves it back.

A few more tickets, and which fits:

  • "Add NightOwl, a carrier at $9 plus $1 a zone." Strategy: a new way of pricing, picked by the customer.
  • "The dispatcher wants to line up tomorrow's reassignments tonight." Command: actions that have to be stored and run later.
  • "A delivered package can be returned, but only if it was delivered." State: what's allowed depends on where the package is.
  • "Let the customer choose between the cheapest and the fastest carrier." Strategy: two ways of choosing, picked from outside.

Where you've already seen them

  • Strategy: a sort handed a comparison, or checkout handed this week's deal in Pass 1.
  • State: a media player whose play button pauses when it's playing and plays when it's paused.
  • Command: Ctrl+Z, and a job queue's jobs.

Check yourself

2 questions to try on the lesson page.

So what

When two patterns draw the same diagram, ask what each object is for: a way of doing a job that the caller picks (Strategy), where something is right now (State), or an action that has to be held (Command). The answer says where the decision belongs.

Key terms

Cheat sheets