Skip to main content

🔍 Command vs Strategy

✅ Purpose of Comparison

Both Command and Strategy patterns aim to abstract behavior into interchangeable objects. However, their goals, application contexts, and control flow roles differ significantly. This comparison outlines their structural differences, use cases, and practical design considerations to help choose the right pattern during architectural decision-making.

✅ Comparison Overview

AspectCommandStrategy
PurposeEncapsulate operations as objectsEncapsulate algorithms or behaviors
UsageAction history, undo/redo, deferred executionBehavior switching at runtime
StructureOperation object + receiver + invokerStrategy interface + concrete strategies
ReusabilityCommands are reusable as standalone actionsStrategies are reusable behavior modules
ExtensionNew actions = new command objectsNew behaviors = new strategy classes
Typical Use CasesGUI actions, batch jobs, undo mechanismsPayment calculation, sorting strategies

✅ Similarities

  • Both encapsulate behavior in objects
  • Use common interfaces to unify invocation structure
  • Enable decoupling between caller and the actual logic
  • Allow behavior replacement via object injection or configuration

✅ Key Differences

AspectCommandStrategy
PurposeEncapsulate actions for invocation, undo, historyEncapsulate algorithms to allow replacement
ResponsibilityRepresents a request or operationRepresents a behavioral policy
Undo Capability✅ Yes, via undo()❌ No built-in support
Invocation ModelUsed by an Invoker, often delayedUsed by a Context to delegate execution
Primary Use CasesUndo/Redo, queues, macrosPayment methods, sorting, formatting, etc.

✅ When to Choose Which

  • ✅ Need to store, queue, or redo actions → Command
  • ✅ Need to switch processing logic or algorithms → Strategy
  • ✅ Want to treat operations as data → Command
  • ✅ Want flexible injection of behavior → Strategy

✅ UML Class Diagram

Command Pattern

Strategy Pattern

✅ Practical Tips for Implementation

  • Use Command when actions need to be tracked, queued, or reversed (e.g., text editors, batch jobs)
  • Use Strategy when different policies or behaviors need to be injected at runtime (e.g., payment, logging)
  • ▶️ Combination possible: A Command might internally use a Strategy to vary the behavior of the executed action.

✅ Summary

  • Command is about representing actions as objects, enabling delayed execution and history management.
  • Strategy is about selecting and injecting behavior, promoting algorithm flexibility and configurability.
  • Despite similar interface shapes, their design intent differs: one focuses on when and how to execute an operation, the other on which behavior to apply.