Command (aka Action | Transaction)

Intent

  • Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Problems

  • How can coupling the invoker of a request to a request be avoided?

  • How can an object be configured with a request?

Solutions

  • Define separate (command) objects that encapsulate a request.

  • A class delegates a request to a command object instead of implementing a particular request directly.

Advantages

✅ Single Responsibility Principle: You can decouple classes that invoke operations from classes that perform these operations. ✅ Open/Closed Principle: You can introduce new commands into the app without breaking existing client code. ✅ You can implement undo/redo. ✅ You can implement deferred execution of operations. ✅ You can assemble a set of simple commands into a complex one.

Disadvantages

❌ The code may become more complicated since you’re introducing a whole new layer between senders and receivers.

Last updated