Command Pattern Geoff Burns 2006 Nov

Preview:

Citation preview

Command Pattern

Also Known As

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.

Motivation

• To issue requests to objects without knowing anything about the operation being requested or the receiver of the request.

Example

Applicability

• O-O replacement for call-back function

• Specify, queue & execute requests at different times

• Support Undo

• Log changes to be reapplied on a crash

• Model system in terms of high-level transactions are build on primitive operations.

Structure

Collaborations

Consequences

• Decouples invoker from implementation of response

• Commands are first-class objects.

• Composite Commands

• Easy to add new commands

Related Patterns

• A Composite can be used to implement Macro-Commands.

• A Memento can keep state the command requires to undo its effect.

• A command that must be copied before being placed on the history list acts as a Prototype.

“Unit of Work” as a collection of Commands Craig Larman

• Register inserts, updates and delete

• Sort for Referential Integrity

• Commit

• Uses Unit of Work Pattern from Patterns of Enterprise Application Architecture by Martin Fowler

Command Processor

POSA Buschmann et al Pattern-Oriented Software Architecture

• Example from Craig Larman (Applying UML and Patterns)

– Server-side request handling

• Queue, log, prioritize and execute commands

Command Processor Intent

• Manages requests as separate objects, schedules their execution and provides additional services such as the storing of request object for later undo.

Command Processor Applicability

• Different modes of user interaction

• External control of application via scripting language

• Implementing crosscutting services e.g. undo, redo, macros, logging, requesting scheduling and suspension.

Command Processor Benefits

• Flexibility in the way requests are activated.

• Flexibility in the number and functionality of requests.

• Programming execution-related services.

• Testability at application level.

• Concurrency.

Command Processor Liabilities

• Efficiency loss.• Potential for an excessive number of command

classes.– Grouping commands– Passing the supplier object as parameter for simple

objects– Macro-command objects that are combinations of

simpler commands.

• Complexity in acquiring command parameters

Command Processor Variants

• Spread controller functionality.

• Combination with Interpreter pattern.

Replace Conditional Dispatcher with CommandJoshua Kerievsky

• Motivation– Not enough runtime flexibility– A bloated body of code

• Benefits– Execute diverse behaviour in a uniform way– Dynamically change timing and behaviour of

response to requests– Trivial Implementation

• Liability– Complicates design