Motivation : Abstract A group of behaviors as objects to decouple behavior requestor and behavior implementers. It also supports recording, revoking, redoing, and transaction processing of behaviors.
Scenario: Consider a series of document operations: open, copy, cut, and paste.
Structure
CodeImplementation
/**/ /*
* Behavior implementer
*/
Namespace Designpattern. Command
{
Public Class Application
{
Public VoidOpenDocument ()
{
}
}
}
/**/ /*
* Behavior implementer
*/
Namespace Designpattern. Command
{
Public Class Document
{
String Path;
Public Document ( String Docpath)
{
Path=Docpath;
}
Public Void Copy ()
{
}
Public Void Cut ()
{
}
Public Void Paste ()
{
}
}
}
/**/ /*
* Behavior object
*/
Namespace Designpattern. Command
{
// Define behavior Interface
Public Interface Icommand
{
VoidExecute ();
}
// Open Document
Public Class Opencommand: icommand
{
// Open a document using an application
Application app;
Public Opencommand (Application)
{
App=Application;
}
Public Void Execute ()
{
App. opendocument ();
}
}
Public Class Copycommand: icommand
{
Document Doc;
Public Copycommand (document)
{
Doc=Document;
}
Public Void Execute ()
{
Doc. Copy ();
}
}
Public Class Cutcommand: icommand
{
Document Doc;
Public Cutcommand (document)
{
Doc=Document;
}
Public Void Execute ()
{
Doc. Cut ();
}
}
Public Class Pastecommand: icommand
{
Document Doc;
Public Pastecommand (document)
{
Doc=Document;
}
Public Void Execute ()
{
Doc. paste ();
}
}
}
/**/ /*
* Behavior requestor
*/
Namespace Designpattern. Command
{
Public Class Client
{
Public Void Dealdocument ()
{< br> document doc = New document ( " documentpath " );
command = New copycommand (DOC);
command. execute ();
}
}
}
Key Points:
1. The basic purpose of this mode is to decouple the behavior requestor and the real-time user. A common implementation method is to abstract the behavior as an object.
2. The specific object that implements the behavior may sometimes save some additional status information as needed, for example, during undo and redo operations.
3. It can be combined with the composite mode to combine multiple commands into complex commands.
4. This mode is similar to delegate. However, there is a difference between the two defined behavior interface specifications: This mode defines behavior interface specifications with "interface-Implementation" in the object-oriented model, which is stricter and more in line with the abstract primitive; delegate defines behavior interface specifications using function signatures, which is more flexible, but has weak abstraction capabilities.