SlideShare a Scribd company logo
4
Most read
14
Most read
Command Pattern
(A Behavioral Pattern)
Command
Intent
  Encapsulate a request as an object, thereby letting you
   parameterize clients with different requests, queue or
   log requests, and support undoable operations.

Also Known As
  Action, Transaction
Motivation
 Sometimes it's necessary to issue requests to objects without knowing anything about the operation being
   requested or the receiver of the request. For example, user interface toolkits include objects like buttons
   and menus that carry out a request in response to user input. But the toolkit can't implement the request
   explicitly in the button or menu, because only applications that use the toolkit know what should be done
   on which object. As toolkit designers we have no way of knowing the receiver of the request or the
   operations that will carry it out.

 The Command pattern lets toolkit objects make requests of unspecified application objects by turning the
   request itself into an object. This object can be stored and passed around like other objects. The key to this
   pattern is an abstract Command class, which declares an interface for executing operations. In the
   simplest form this interface includes an abstract Execute operation. Concrete Command subclasses specify
   a receiver-action pair by storing the receiver as an instance variable and by implementing Execute to
   invoke the request. The receiver has the knowledge required to carry out the request.

 Menus can be implemented easily with Command objects. Each choice in a Menu is an instance of a
   MenuItem class. An Application class creates these menus and their menu items along with the rest of the
   user interface. The Application class also keeps track of Document objects that a user has opened.

 The application configures each MenuItem with an instance of a concrete Command subclass. When the
   user selects a MenuItem, the MenuItem calls Execute on its command, and Execute carries out the
   operation. MenuItems don't know which subclass of Command they use. Command subclasses store the
   receiver of the request and invoke one or more operations on the receiver.
Motivation




 For example, PasteCommand supports pasting text from the clipboard into a Document.
  PasteCommand's receiver is the Document object it is supplied upon instantiation. The
  Execute operation invokes Paste on the receiving Document.
Motivation
Motivation
Applicability
 Use the Command pattern when you want to

     parameterize objects by an action to perform, as MenuItem objects did above. You can express such parameterization
       in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later
       point. Commands are an object-oriented replacement for callbacks.

     specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the
       original request. If the receiver of a request can be represented in an address space-independent way, then you can
       transfer a command object for the request to a different process and fulfill the request there.

     support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The
       Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute.
       Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list
       backwards and forwards calling Unexecute and Execute, respectively.

     support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command
       interface with load and store operations, you can keep a persistent log of changes. Recovering from a crash involves
       reloading logged commands from disk and reexecuting them with the Execute operation.

     structure a system around high-level operations built on primitives operations. Such a structure is common in
       information systems that support transactions. A transaction encapsulates a set of changes to data. The Command
       pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions
       the same way. The pattern also makes it easy to extend the system with new transactions.
Structure

Participants
 Command
    declares an interface for executing an operation.
 ConcreteCommand (PasteCommand, OpenCommand)
    defines a binding between a Receiver object and an action.
    implements Execute by invoking the corresponding operation(s) on
     Receiver.
 Client (Application)
    creates a ConcreteCommand object and sets its receiver.
 Invoker (MenuItem)
    asks the command to carry out the request.
 Receiver (Document, Application)
    knows how to perform the operations associated with carrying out a
     request. Any class may serve as a Receiver.
Collaborations
 The client creates a ConcreteCommand object and specifies its receiver.
 An Invoker object stores the ConcreteCommand object.
 The invoker issues a request by calling Execute on the command. When commands are undoable,
  ConcreteCommand stores state for undoing the command prior to invoking Execute.
 The ConcreteCommand object invokes operations on its receiver to carry out the request.
 The following diagram shows the interactions between these objects. It illustrates how Command
  decouples the invoker from the receiver (and the request it carries out).
Consequences
 The Command pattern has the following consequences:
 Command decouples the object that invokes the operation from the one that
  knows how to perform it.
 Commands are first-class objects. They can be manipulated and extended like
  any other object.
 You can assemble commands into a composite command. An example is the
  MacroCommand class described earlier. In general, composite commands are
  an instance of the Composite pattern.
 It's easy to add new Commands, because you don't have to change existing
  classes.
Implementation
 Consider the following issues when implementing the Command pattern:
 How intelligent should a command be? A command can have a wide range of abilities. At one
  extreme it merely defines a binding between a receiver and the actions that carry out the request. At
  the other extreme it implements everything itself without delegating to a receiver at all. The latter
  extreme is useful when you want to define commands that are independent of existing classes, when
  no suitable receiver exists, or when a command knows its receiver implicitly. For example, a
  command that creates another application window may be just as capable of creating the window as
  any other object. Somewhere in between these extremes are commands that have enough
  knowledge to find their receiver dynamically.
 Supporting undo and redo. Commands can support undo and redo capabilities if they provide a way
  to reverse their execution (e.g., an Unexecute or Undo operation). A ConcreteCommand class might
  need to store additional state to do so. This state can include
      the Receiver object, which actually carries out operations in response to the request,
      the arguments to the operation performed on the receiver, and
      any original values in the receiver that can change as a result of handling the request. The receiver must provide
        operations that let the command return the receiver to its prior state.
 To support one level of undo, an application needs to store only the command that was executed
   last. For multiple-level undo and redo, the application needs a history list of commands that have
   been executed, where the maximum length of the list determines the number of undo/redo levels.
   The history list stores sequences of commands that have been executed. Traversing backward
   through the list and reverse-executing commands cancels their effect; traversing forward and
   executing commands reexecutes them.
Implementation
 An undoable command might have to be copied before it can be placed on the history list. That's
   because the command object that carried out the original request, say, from a MenuItem, will
   perform other requests at later times. Copying is required to distinguish different invocations of the
   same command if its state can vary across invocations.

 For example, a DeleteCommand that deletes selected objects must store different sets of objects each
   time it's executed. Therefore the DeleteCommand object must be copied following execution, and
   the copy is placed on the history list. If the command's state never changes on execution, then
   copying is not required—only a reference to the command need be placed on the history list.
   Commands that must be copied before being placed on the history list act as prototypes (see
   Prototype ).

 Avoiding error accumulation in the undo process. Hysteresis can be a problem in ensuring a reliable,
  semantics-preserving undo/redo mechanism. Errors can accumulate as commands are executed,
  unexecuted, and reexecuted repeatedly so that an application's state eventually diverges from
  original values. It may be necessary therefore to store more information in the command to ensure
  that objects are restored to their original state. The Memento pattern can be applied to give the
  command access to this information without exposing the internals of other objects.
 Using C++ templates. For commands that (1) aren't undoable and (2) don't require arguments, we
  can use C++ templates to avoid creating a Command subclass for every kind of action and receiver.
  We show how to do this in the Sample Code section.
Assignment
 Develop a windows/web based word processor (like notepad) with
  undo-redo support while typing.

More Related Content

PPT
Command Design Pattern
Shahriar Hyder
 
PPT
Command Pattern
Geoff Burns
 
PPT
Introduction to design patterns
Amit Kabra
 
PPTX
Software Development Life Cycle
Slideshare
 
PPTX
Command Design Pattern
Rothana Choun
 
PPTX
Gof design patterns
Srikanth R Vaka
 
PDF
Java Design Patterns Tutorial | Edureka
Edureka!
 
PDF
Code Smells and Its type (With Example)
Anshul Vinayak
 
Command Design Pattern
Shahriar Hyder
 
Command Pattern
Geoff Burns
 
Introduction to design patterns
Amit Kabra
 
Software Development Life Cycle
Slideshare
 
Command Design Pattern
Rothana Choun
 
Gof design patterns
Srikanth R Vaka
 
Java Design Patterns Tutorial | Edureka
Edureka!
 
Code Smells and Its type (With Example)
Anshul Vinayak
 

What's hot (20)

PPTX
Ngrx: Redux in angular
Saadnoor Salehin
 
PDF
Software Development Life Cycle (SDLC)
Mohamed Sami El-Tahawy
 
PPTX
Creational pattern
Himanshu
 
PDF
Design patterns
abhisheksagi
 
PPTX
Agile Software Development Model
Ritika Balagan
 
PPTX
React hooks
Assaf Gannon
 
PPTX
Strategy Pattern
Guo Albert
 
PPT
Collaboration Diagram
fahad_uaar
 
PPT
Refactoring Tips by Martin Fowler
Igor Crvenov
 
PPTX
Design Pattern - Factory Method Pattern
Mudasir Qazi
 
PPTX
Refactoring and code smells
Paul Nguyen
 
PPT
Command Design Pattern
anil kanzariya
 
PPTX
The Singleton Pattern Presentation
JAINIK PATEL
 
PPTX
Feature driven development (FDD)
LennonDukeDuero
 
PPT
Object Oriented Design
Sudarsun Santhiappan
 
PPTX
Let us understand design pattern
Mindfire Solutions
 
PPTX
Agile Methodology PPT
Mohit Kumar
 
PPTX
Software requirement and specification
Aman Adhikari
 
PPT
Iterator Design Pattern
Varun Arora
 
Ngrx: Redux in angular
Saadnoor Salehin
 
Software Development Life Cycle (SDLC)
Mohamed Sami El-Tahawy
 
Creational pattern
Himanshu
 
Design patterns
abhisheksagi
 
Agile Software Development Model
Ritika Balagan
 
React hooks
Assaf Gannon
 
Strategy Pattern
Guo Albert
 
Collaboration Diagram
fahad_uaar
 
Refactoring Tips by Martin Fowler
Igor Crvenov
 
Design Pattern - Factory Method Pattern
Mudasir Qazi
 
Refactoring and code smells
Paul Nguyen
 
Command Design Pattern
anil kanzariya
 
The Singleton Pattern Presentation
JAINIK PATEL
 
Feature driven development (FDD)
LennonDukeDuero
 
Object Oriented Design
Sudarsun Santhiappan
 
Let us understand design pattern
Mindfire Solutions
 
Agile Methodology PPT
Mohit Kumar
 
Software requirement and specification
Aman Adhikari
 
Iterator Design Pattern
Varun Arora
 
Ad

Viewers also liked (20)

PDF
Design patterns - Singleton&Command
Kai Aras
 
PPT
Command and Adapter Pattern
Jonathan Simon
 
PPT
Generalized Functors - Realizing Command Design Pattern in C++
ppd1961
 
PPT
Composite Design Pattern
Ferdous Mahmud Shaon
 
PPTX
The State Design Pattern
Josh Candish
 
PDF
An Introduction to
melbournepatterns
 
PPTX
Command Pattern
melbournepatterns
 
PPTX
Command Pattern
guest271c51
 
PDF
Client-Server-Kommunikation mit dem Command Pattern
pgt technology scouting GmbH
 
PPTX
Model View Command Pattern
Akash Kava
 
PDF
Command Pattern in Ruby
Jyaasa Technologies
 
PPT
Design Patterns
ppd1961
 
PPTX
Proxy Pattern
Hüseyin Ergin
 
PPTX
Design Pattern lecture 4
Julie Iskander
 
PPTX
Chain of Responsibility Pattern
Hélio Costa e Silva
 
PPS
Bridge Pattern Derek Weeks
melbournepatterns
 
PPT
Bridge pattern
Shakil Ahmed
 
PDF
Bridge Pattern
Somenath Mukhopadhyay
 
PPT
20120420 - Design pattern bridge
LearningTech
 
PPT
Bridge Design Pattern
sahilrk911
 
Design patterns - Singleton&Command
Kai Aras
 
Command and Adapter Pattern
Jonathan Simon
 
Generalized Functors - Realizing Command Design Pattern in C++
ppd1961
 
Composite Design Pattern
Ferdous Mahmud Shaon
 
The State Design Pattern
Josh Candish
 
An Introduction to
melbournepatterns
 
Command Pattern
melbournepatterns
 
Command Pattern
guest271c51
 
Client-Server-Kommunikation mit dem Command Pattern
pgt technology scouting GmbH
 
Model View Command Pattern
Akash Kava
 
Command Pattern in Ruby
Jyaasa Technologies
 
Design Patterns
ppd1961
 
Proxy Pattern
Hüseyin Ergin
 
Design Pattern lecture 4
Julie Iskander
 
Chain of Responsibility Pattern
Hélio Costa e Silva
 
Bridge Pattern Derek Weeks
melbournepatterns
 
Bridge pattern
Shakil Ahmed
 
Bridge Pattern
Somenath Mukhopadhyay
 
20120420 - Design pattern bridge
LearningTech
 
Bridge Design Pattern
sahilrk911
 
Ad

Similar to Command pattern (20)

PDF
Command pattern in java
RakibAhmed0
 
PPT
Command Pattern Geoff Burns 2006 Nov
melbournepatterns
 
PPT
Lesson10 behavioral patterns
OktJona
 
PPTX
Behavioral pattern 4
Naga Muruga
 
PDF
Apache commons chain in Spring Framework
Nivedita Mondal
 
DOCX
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
PDF
How to build a react native app with the help of react native hooks
Katy Slemon
 
PPTX
Function & procedure
atishupadhyay
 
DOCX
Memento Pattern Implementation
Steve Widom
 
DOCX
What is the difference between struts 1 vs struts 2
Santosh Singh Paliwal
 
PPTX
Design Patterns
Ankit.Rustagi
 
ODP
Lagom - Persistent Entity
Knoldus Inc.
 
PPT
Introduction to the INTEGRAL FRAMEWORK
Karthik Subramanian
 
PPT
Introduction to the integral framework
Karthik Subramanian
 
PPTX
Vmware vSphere Api Best Practices
Pablo Roesch
 
PPTX
Redux
Maulik Shah
 
PPTX
Android service, aidl - day 1
Utkarsh Mankad
 
PDF
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...
Codemotion
 
PPTX
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
PDF
Understanding react hooks
Samundra khatri
 
Command pattern in java
RakibAhmed0
 
Command Pattern Geoff Burns 2006 Nov
melbournepatterns
 
Lesson10 behavioral patterns
OktJona
 
Behavioral pattern 4
Naga Muruga
 
Apache commons chain in Spring Framework
Nivedita Mondal
 
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
How to build a react native app with the help of react native hooks
Katy Slemon
 
Function & procedure
atishupadhyay
 
Memento Pattern Implementation
Steve Widom
 
What is the difference between struts 1 vs struts 2
Santosh Singh Paliwal
 
Design Patterns
Ankit.Rustagi
 
Lagom - Persistent Entity
Knoldus Inc.
 
Introduction to the INTEGRAL FRAMEWORK
Karthik Subramanian
 
Introduction to the integral framework
Karthik Subramanian
 
Vmware vSphere Api Best Practices
Pablo Roesch
 
Android service, aidl - day 1
Utkarsh Mankad
 
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...
Codemotion
 
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
Understanding react hooks
Samundra khatri
 

More from Shakil Ahmed (20)

PPT
Algorithm
Shakil Ahmed
 
PPT
B-tree & R-tree
Shakil Ahmed
 
PPTX
Advanced data structure
Shakil Ahmed
 
PPT
Prototype pattern
Shakil Ahmed
 
PPT
Observer pattern
Shakil Ahmed
 
PPT
Mediator pattern
Shakil Ahmed
 
PPT
Flyweight pattern
Shakil Ahmed
 
PPT
Facade pattern
Shakil Ahmed
 
PPT
Composite pattern
Shakil Ahmed
 
PPT
Chain of responsibility
Shakil Ahmed
 
PPT
Builder pattern
Shakil Ahmed
 
PPT
Adapter pattern
Shakil Ahmed
 
PPT
Proxy pattern
Shakil Ahmed
 
PPT
iOS 5
Shakil Ahmed
 
PPT
Ios development
Shakil Ahmed
 
PPT
Graph
Shakil Ahmed
 
PPT
Lowest common ancestor
Shakil Ahmed
 
PPT
Segment tree
Shakil Ahmed
 
PPT
Tree & bst
Shakil Ahmed
 
PPT
Trie tree
Shakil Ahmed
 
Algorithm
Shakil Ahmed
 
B-tree & R-tree
Shakil Ahmed
 
Advanced data structure
Shakil Ahmed
 
Prototype pattern
Shakil Ahmed
 
Observer pattern
Shakil Ahmed
 
Mediator pattern
Shakil Ahmed
 
Flyweight pattern
Shakil Ahmed
 
Facade pattern
Shakil Ahmed
 
Composite pattern
Shakil Ahmed
 
Chain of responsibility
Shakil Ahmed
 
Builder pattern
Shakil Ahmed
 
Adapter pattern
Shakil Ahmed
 
Proxy pattern
Shakil Ahmed
 
Ios development
Shakil Ahmed
 
Lowest common ancestor
Shakil Ahmed
 
Segment tree
Shakil Ahmed
 
Tree & bst
Shakil Ahmed
 
Trie tree
Shakil Ahmed
 

Recently uploaded (20)

PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PDF
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PPTX
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
PDF
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Landforms and landscapes data surprise preview
jpinnuck
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
Understanding operators in c language.pptx
auteharshil95
 
PPTs-The Rise of Empiresghhhhhhhh (1).pptx
academysrusti114
 
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 

Command pattern

  • 2. Command Intent Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. Also Known As Action, Transaction
  • 3. Motivation  Sometimes it's necessary to issue requests to objects without knowing anything about the operation being requested or the receiver of the request. For example, user interface toolkits include objects like buttons and menus that carry out a request in response to user input. But the toolkit can't implement the request explicitly in the button or menu, because only applications that use the toolkit know what should be done on which object. As toolkit designers we have no way of knowing the receiver of the request or the operations that will carry it out.  The Command pattern lets toolkit objects make requests of unspecified application objects by turning the request itself into an object. This object can be stored and passed around like other objects. The key to this pattern is an abstract Command class, which declares an interface for executing operations. In the simplest form this interface includes an abstract Execute operation. Concrete Command subclasses specify a receiver-action pair by storing the receiver as an instance variable and by implementing Execute to invoke the request. The receiver has the knowledge required to carry out the request.  Menus can be implemented easily with Command objects. Each choice in a Menu is an instance of a MenuItem class. An Application class creates these menus and their menu items along with the rest of the user interface. The Application class also keeps track of Document objects that a user has opened.  The application configures each MenuItem with an instance of a concrete Command subclass. When the user selects a MenuItem, the MenuItem calls Execute on its command, and Execute carries out the operation. MenuItems don't know which subclass of Command they use. Command subclasses store the receiver of the request and invoke one or more operations on the receiver.
  • 4. Motivation  For example, PasteCommand supports pasting text from the clipboard into a Document. PasteCommand's receiver is the Document object it is supplied upon instantiation. The Execute operation invokes Paste on the receiving Document.
  • 7. Applicability  Use the Command pattern when you want to  parameterize objects by an action to perform, as MenuItem objects did above. You can express such parameterization in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later point. Commands are an object-oriented replacement for callbacks.  specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address space-independent way, then you can transfer a command object for the request to a different process and fulfill the request there.  support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.  support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes. Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.  structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.
  • 9. Participants  Command  declares an interface for executing an operation.  ConcreteCommand (PasteCommand, OpenCommand)  defines a binding between a Receiver object and an action.  implements Execute by invoking the corresponding operation(s) on Receiver.  Client (Application)  creates a ConcreteCommand object and sets its receiver.  Invoker (MenuItem)  asks the command to carry out the request.  Receiver (Document, Application)  knows how to perform the operations associated with carrying out a request. Any class may serve as a Receiver.
  • 10. Collaborations  The client creates a ConcreteCommand object and specifies its receiver.  An Invoker object stores the ConcreteCommand object.  The invoker issues a request by calling Execute on the command. When commands are undoable, ConcreteCommand stores state for undoing the command prior to invoking Execute.  The ConcreteCommand object invokes operations on its receiver to carry out the request.  The following diagram shows the interactions between these objects. It illustrates how Command decouples the invoker from the receiver (and the request it carries out).
  • 11. Consequences  The Command pattern has the following consequences:  Command decouples the object that invokes the operation from the one that knows how to perform it.  Commands are first-class objects. They can be manipulated and extended like any other object.  You can assemble commands into a composite command. An example is the MacroCommand class described earlier. In general, composite commands are an instance of the Composite pattern.  It's easy to add new Commands, because you don't have to change existing classes.
  • 12. Implementation  Consider the following issues when implementing the Command pattern:  How intelligent should a command be? A command can have a wide range of abilities. At one extreme it merely defines a binding between a receiver and the actions that carry out the request. At the other extreme it implements everything itself without delegating to a receiver at all. The latter extreme is useful when you want to define commands that are independent of existing classes, when no suitable receiver exists, or when a command knows its receiver implicitly. For example, a command that creates another application window may be just as capable of creating the window as any other object. Somewhere in between these extremes are commands that have enough knowledge to find their receiver dynamically.  Supporting undo and redo. Commands can support undo and redo capabilities if they provide a way to reverse their execution (e.g., an Unexecute or Undo operation). A ConcreteCommand class might need to store additional state to do so. This state can include  the Receiver object, which actually carries out operations in response to the request,  the arguments to the operation performed on the receiver, and  any original values in the receiver that can change as a result of handling the request. The receiver must provide operations that let the command return the receiver to its prior state.  To support one level of undo, an application needs to store only the command that was executed last. For multiple-level undo and redo, the application needs a history list of commands that have been executed, where the maximum length of the list determines the number of undo/redo levels. The history list stores sequences of commands that have been executed. Traversing backward through the list and reverse-executing commands cancels their effect; traversing forward and executing commands reexecutes them.
  • 13. Implementation  An undoable command might have to be copied before it can be placed on the history list. That's because the command object that carried out the original request, say, from a MenuItem, will perform other requests at later times. Copying is required to distinguish different invocations of the same command if its state can vary across invocations.  For example, a DeleteCommand that deletes selected objects must store different sets of objects each time it's executed. Therefore the DeleteCommand object must be copied following execution, and the copy is placed on the history list. If the command's state never changes on execution, then copying is not required—only a reference to the command need be placed on the history list. Commands that must be copied before being placed on the history list act as prototypes (see Prototype ).  Avoiding error accumulation in the undo process. Hysteresis can be a problem in ensuring a reliable, semantics-preserving undo/redo mechanism. Errors can accumulate as commands are executed, unexecuted, and reexecuted repeatedly so that an application's state eventually diverges from original values. It may be necessary therefore to store more information in the command to ensure that objects are restored to their original state. The Memento pattern can be applied to give the command access to this information without exposing the internals of other objects.  Using C++ templates. For commands that (1) aren't undoable and (2) don't require arguments, we can use C++ templates to avoid creating a Command subclass for every kind of action and receiver. We show how to do this in the Sample Code section.
  • 14. Assignment  Develop a windows/web based word processor (like notepad) with undo-redo support while typing.