SlideShare ist ein Scribd-Unternehmen logo
1 von 14
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.

Weitere ähnliche Inhalte

Was ist angesagt?

Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Chain of responsibility pattern
Chain of responsibility patternChain of responsibility pattern
Chain of responsibility patternKuntanSutar
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design PatternAdeel Riaz
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET frameworkRicha Handa
 
Domain State model OOAD
Domain State model  OOADDomain State model  OOAD
Domain State model OOADRaghu Kumar
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
The State Design Pattern
The State Design PatternThe State Design Pattern
The State Design PatternJosh Candish
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 

Was ist angesagt? (20)

Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Chain of responsibility pattern
Chain of responsibility patternChain of responsibility pattern
Chain of responsibility pattern
 
Factory Design Pattern
Factory Design PatternFactory Design Pattern
Factory Design Pattern
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
 
Proxy Pattern
Proxy PatternProxy Pattern
Proxy Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
VB.NET:An introduction to Namespaces in .NET framework
VB.NET:An introduction to  Namespaces in .NET frameworkVB.NET:An introduction to  Namespaces in .NET framework
VB.NET:An introduction to Namespaces in .NET framework
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Domain State model OOAD
Domain State model  OOADDomain State model  OOAD
Domain State model OOAD
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
The State Design Pattern
The State Design PatternThe State Design Pattern
The State Design Pattern
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 

Andere mochten auch

Design patterns - Singleton&Command
Design patterns - Singleton&CommandDesign patterns - Singleton&Command
Design patterns - Singleton&CommandKai Aras
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter PatternJonathan Simon
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++ppd1961
 
Client-Server-Kommunikation mit dem Command Pattern
Client-Server-Kommunikation mit dem Command PatternClient-Server-Kommunikation mit dem Command Pattern
Client-Server-Kommunikation mit dem Command Patternpgt technology scouting GmbH
 
Model View Command Pattern
Model View Command PatternModel View Command Pattern
Model View Command PatternAkash Kava
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsppd1961
 
Design Pattern lecture 4
Design Pattern lecture 4Design Pattern lecture 4
Design Pattern lecture 4Julie Iskander
 
20120420 - Design pattern bridge
20120420 - Design pattern bridge20120420 - Design pattern bridge
20120420 - Design pattern bridgeLearningTech
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Patternsahilrk911
 
Abstract Factory Pattern
Abstract Factory PatternAbstract Factory Pattern
Abstract Factory Patternguestcb0002
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution ReportFridz Felisco
 

Andere mochten auch (20)

Design patterns - Singleton&Command
Design patterns - Singleton&CommandDesign patterns - Singleton&Command
Design patterns - Singleton&Command
 
Command and Adapter Pattern
Command and Adapter PatternCommand and Adapter Pattern
Command and Adapter Pattern
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Composite Design Pattern
Composite Design PatternComposite Design Pattern
Composite Design Pattern
 
An Introduction to
An Introduction to An Introduction to
An Introduction to
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
 
Command Pattern
Command PatternCommand Pattern
Command Pattern
 
Client-Server-Kommunikation mit dem Command Pattern
Client-Server-Kommunikation mit dem Command PatternClient-Server-Kommunikation mit dem Command Pattern
Client-Server-Kommunikation mit dem Command Pattern
 
Model View Command Pattern
Model View Command PatternModel View Command Pattern
Model View Command Pattern
 
Command Pattern in Ruby
Command Pattern in RubyCommand Pattern in Ruby
Command Pattern in Ruby
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design Pattern lecture 4
Design Pattern lecture 4Design Pattern lecture 4
Design Pattern lecture 4
 
Chain of Responsibility Pattern
Chain of Responsibility PatternChain of Responsibility Pattern
Chain of Responsibility Pattern
 
Bridge Pattern Derek Weeks
Bridge Pattern   Derek WeeksBridge Pattern   Derek Weeks
Bridge Pattern Derek Weeks
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
Bridge Pattern
Bridge PatternBridge Pattern
Bridge Pattern
 
20120420 - Design pattern bridge
20120420 - Design pattern bridge20120420 - Design pattern bridge
20120420 - Design pattern bridge
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Abstract Factory Pattern
Abstract Factory PatternAbstract Factory Pattern
Abstract Factory Pattern
 
Retail Institution Report
Retail Institution ReportRetail Institution Report
Retail Institution Report
 

Ähnlich wie Command pattern

Command pattern in java
Command pattern in javaCommand pattern in java
Command pattern in javaRakibAhmed0
 
Command Pattern Geoff Burns 2006 Nov
Command Pattern Geoff Burns 2006 NovCommand Pattern Geoff Burns 2006 Nov
Command Pattern Geoff Burns 2006 Novmelbournepatterns
 
Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patternsOktJona
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4Naga Muruga
 
Apache commons chain in Spring Framework
Apache commons chain in Spring FrameworkApache commons chain in Spring Framework
Apache commons chain in Spring FrameworkNivedita Mondal
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksKaty Slemon
 
Function & procedure
Function & procedureFunction & procedure
Function & procedureatishupadhyay
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern ImplementationSteve Widom
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2Santosh Singh Paliwal
 
Lagom - Persistent Entity
Lagom - Persistent EntityLagom - Persistent Entity
Lagom - Persistent EntityKnoldus Inc.
 
Introduction to the INTEGRAL FRAMEWORK
Introduction to the INTEGRAL FRAMEWORKIntroduction to the INTEGRAL FRAMEWORK
Introduction to the INTEGRAL FRAMEWORKKarthik Subramanian
 
Introduction to the integral framework
Introduction to the integral frameworkIntroduction to the integral framework
Introduction to the integral frameworkKarthik Subramanian
 
Vmware vSphere Api Best Practices
Vmware vSphere Api Best PracticesVmware vSphere Api Best Practices
Vmware vSphere Api Best PracticesPablo Roesch
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1Utkarsh Mankad
 
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...Codemotion
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A ReviewFernando Torres
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 

Ähnlich wie Command pattern (20)

Command pattern in java
Command pattern in javaCommand pattern in java
Command pattern in java
 
Command Pattern Geoff Burns 2006 Nov
Command Pattern Geoff Burns 2006 NovCommand Pattern Geoff Burns 2006 Nov
Command Pattern Geoff Burns 2006 Nov
 
Lesson10 behavioral patterns
Lesson10 behavioral patternsLesson10 behavioral patterns
Lesson10 behavioral patterns
 
Behavioral pattern 4
Behavioral pattern 4Behavioral pattern 4
Behavioral pattern 4
 
Apache commons chain in Spring Framework
Apache commons chain in Spring FrameworkApache commons chain in Spring Framework
Apache commons chain in Spring Framework
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
How to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooksHow to build a react native app with the help of react native hooks
How to build a react native app with the help of react native hooks
 
Function & procedure
Function & procedureFunction & procedure
Function & procedure
 
Memento Pattern Implementation
Memento Pattern ImplementationMemento Pattern Implementation
Memento Pattern Implementation
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Lagom - Persistent Entity
Lagom - Persistent EntityLagom - Persistent Entity
Lagom - Persistent Entity
 
Introduction to the INTEGRAL FRAMEWORK
Introduction to the INTEGRAL FRAMEWORKIntroduction to the INTEGRAL FRAMEWORK
Introduction to the INTEGRAL FRAMEWORK
 
Introduction to the integral framework
Introduction to the integral frameworkIntroduction to the integral framework
Introduction to the integral framework
 
Vmware vSphere Api Best Practices
Vmware vSphere Api Best PracticesVmware vSphere Api Best Practices
Vmware vSphere Api Best Practices
 
Redux
ReduxRedux
Redux
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...
Massimo Bonanni - Workflow as code with Azure Durable Functions - Codemotion ...
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 

Mehr von Shakil Ahmed

Mehr von Shakil Ahmed (17)

Algorithm
AlgorithmAlgorithm
Algorithm
 
B-tree & R-tree
B-tree & R-treeB-tree & R-tree
B-tree & R-tree
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
iOS 5
iOS 5iOS 5
iOS 5
 
Ios development
Ios developmentIos development
Ios development
 
Graph
GraphGraph
Graph
 
Lowest common ancestor
Lowest common ancestorLowest common ancestor
Lowest common ancestor
 
Segment tree
Segment treeSegment tree
Segment tree
 
Tree & bst
Tree & bstTree & bst
Tree & bst
 
Trie tree
Trie treeTrie tree
Trie tree
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Advanced Search Techniques
Advanced Search TechniquesAdvanced Search Techniques
Advanced Search Techniques
 

Kürzlich hochgeladen

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 

Kürzlich hochgeladen (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

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.