CSC/ECE 517 Fall 2012/ch2b 2w45 pg: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(22 intermediate revisions by 2 users not shown)
Line 5: Line 5:
This wiki page provides a directory of sites for Command Design Pattern that will help readers to know what each website contains, why should readers refer one website over another and a list of examples that readers can look up to understand the Command Pattern.
This wiki page provides a directory of sites for Command Design Pattern that will help readers to know what each website contains, why should readers refer one website over another and a list of examples that readers can look up to understand the Command Pattern.


<b>Introduction</b><br>
= <b>Introduction</b><br> =


<b>[http://en.wikipedia.org/wiki/Command_pattern Definition:]</b><br>
<b>[http://en.wikipedia.org/wiki/Command_pattern Definition:]</b><br>
Line 24: Line 24:
Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters.
Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters.
   
   
http://upload.wikimedia.org/wikipedia/commons/8/8e/Command_Design_Pattern_Class_Diagram.png
[[File:2.jpg]]


<br><b>
<b>
[http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/patexamples.html Command Real world Example ]</b><br>
[http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/patexamples.html Command Real world Example ]</b><br>


The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parameterized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order, or command from a customer, and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of "checks" used by different diners is not dependent on the menu, and therefore they can support commands to cook many different items.
The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parameterized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order, or command from a customer, and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of "checks" used by different diners is not dependent on the menu, and therefore they can support commands to cook many different items.


[[File:http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/pateximg14.gif]]
[[File: pateximg14.gif]]
<b><br>When Would I Use This Pattern?</b><br>
 
<b>When Would I Use This Pattern?</b><br>
The Command Pattern is useful when:<br>
The Command Pattern is useful when:<br>
• A history of requests is needed<br>
• A history of requests is needed<br>
Line 39: Line 40:
• The invoker should be decoupled from the object handling the invocation.<br>
• The invoker should be decoupled from the object handling the invocation.<br>
You'll see command being used a lot when you need to have multiple undo operations, where a stack of the recently executed commands are maintained. To implement the undo, all you need to do is get the last Command in the stack and execute it's undo() method.
You'll see command being used a lot when you need to have multiple undo operations, where a stack of the recently executed commands are maintained. To implement the undo, all you need to do is get the last Command in the stack and execute it's undo() method.
You'll also find Command useful for wizards, progress bars, GUI buttons and menu actions, and other transactional behavior.  
You'll also find Command useful for wizards, progress bars, GUI buttons and menu actions, and other transactional behavior.
 
<br><b>Directory of sites</b><br>


= <b>Directory of sites</b><br> =
== <b>[http://msdn.microsoft.com/en-us/magazine/cc163920.aspx Command pattern on MSDN Microsoft Website] </b><br> ==
Command Pattern to -Simplify Distributed System Design Using the Command Pattern, MSMQ, and .NET


<b>[http://msdn.microsoft.com/en-us/magazine/cc163920.aspx Command pattern on MSDN Microsoft Website] </b><br>
<b>Object-based collaboration VS service-based collaboration</b><br>
Command Pattern to -Simplify Distributed System Design Using the Command Pattern, MSMQ, and .NET


<br><b>Object-based collaboration VS service-based collaboration</b><br>
Communication or exchange of request and service and the format or the pattern based on play an important criteria in successful implementation of  object-based collaboration and service-oriented architecture.  
Communication or exchange of request and service and the format or the pattern based on play an important criteria in successful implementation of  object-based collaboration and service-oriented architecture.  
<br>
<br>
Systems generally share a common platform, allowing you to optimize in ways you can't on widely dispersed -systems that span various operating systems and development environments are preferred to follow object-based collaboration than service-based collaboration.
Systems generally share a common platform, allowing you to optimize in ways you can't on widely dispersed -systems that span various operating systems and development environments are preferred to follow object-based collaboration than service-based collaboration.
<br>
<br>
But generally the participants are hybrid and they don't share a common platform,  in such situations service oriented architecture comes handy. Here the requests are queued in Microsoft Message Queuing (MSMQ) which implements Command design pattern.  
But generally the participants are hybrid and they don't share a common platform,  in such situations service oriented architecture comes handy. Here the requests are queued in Microsoft Message Queuing (MSMQ) which implements Command design pattern.  


[[File:http://i.msdn.microsoft.com/cc163920.fig02(en-us).gif]]
[[File:3.gif]]


The distributed command system discussed here is the combination of reliable messaging, services, and the Command pattern. While most often seen as a design pattern for implementing desktop application menu systems, the Command pattern offers advantages for distributed systems when combined with a robust messaging infrastructure like MSMQ.  
The distributed command system discussed here is the combination of reliable messaging, services, and the Command pattern. While most often seen as a design pattern for implementing desktop application menu systems, the Command pattern offers advantages for distributed systems when combined with a robust messaging infrastructure like MSMQ.  


<br><b>Learning: </b><br>
[[File:4.gif]]
 
<b>Learning: </b><br>
 
The concept is very simple, in service oriented architecture, the participants don't share a common platform, hence you need a mechanism, a design pattern, a module to issue requests to objects.   
The concept is very simple, in service oriented architecture, the participants don't share a common platform, hence you need a mechanism, a design pattern, a module to issue requests to objects.   
<br>
<br>
Line 66: Line 69:
Pattern and Participants
Pattern and Participants
<pre>
<pre>
Class Description
Class               Description
Command Abstract base class for all Command objects
Command               Abstract base class for all Command objects
Concrete command Any number of classes derived from Command
Concrete command     Any number of classes derived from Command
Client The creator of a command
Client               The creator of a command
Invoker Executes a command
Invoker               Executes a command
Receiver Any class that is acted on by a command
Receiver       Any class that is acted on by a command
</pre>
</pre>


<br><b>Another Example: </b><br>
<br><b>Another Example: </b><br>
In ASP.NET, the database communication are based on the commands, the database commands such as create connection, command statement, parameter doesn't know what the object is and what the object it is requesting and these are typical example of command design pattern it best.
In ASP.NET, the database communication are based on the commands, the database commands such as create connection, command statement, parameter doesn't know what the object is and what the object it is requesting and these are typical example of command design pattern it best.
<br><b>
<br><b>
Conclusion</b><br>
Conclusion</b><br>
The Command pattern specifies a set of interactions that you can apply to the development of distributed systems in .NET. Use this pattern in your application to implement a high-performance, extendable backbone connecting your near link nodes that run .NET-enabled operating systems to achieve optimal performance and rapid development. Distributed commands are a mix of classic object orientation, messaging, and service architecture that together fill a definite need in the distributed systems space.
The Command pattern specifies a set of interactions that you can apply to the development of distributed systems in .NET. Use this pattern in your application to implement a high-performance, extendable backbone connecting your near link nodes that run .NET-enabled operating systems to achieve optimal performance and rapid development. Distributed commands are a mix of classic object orientation, messaging, and service architecture that together fill a definite need in the distributed systems space.
<b><br>
 
[http://www.codeproject.com/Articles/12263/The-Command-Pattern-and-MVC-Architecture Advantages]</b> <br>
<b>[http://www.codeproject.com/Articles/12263/The-Command-Pattern-and-MVC-Architecture Advantages]</b> <br>  


The benefit of the Command class is that it makes it easier to add new functions to an application.  
The benefit of the Command class is that it makes it easier to add new functions to an application.  
Line 87: Line 92:
When the Command gets passed to the Controller, the Controller can use it to route the request, without knowing anything about it.
When the Command gets passed to the Controller, the Controller can use it to route the request, without knowing anything about it.


<b><br>Disadvantages:</b><br>
<b>Disadvantages:</b><br>
The major disadvantage of the pattern is that it results in lots of little Command classes that can clutter up a design.  
The major disadvantage of the pattern is that it results in lots of little Command classes that can clutter up a design.  
<br>
<br>
Line 94: Line 99:
The resulting bloat may necessitate partitioning the Controller into a subsystem, and it will certainly make the Controller harder to understand and maintain.
The resulting bloat may necessitate partitioning the Controller into a subsystem, and it will certainly make the Controller harder to understand and maintain.


<br>
== [http://www.phpwact.org/ Command Pattern on Web Application Component Toolkit (WACT)]<br> ==
[http://www.phpwact.org/ Command Pattern on Web Application Component Toolkit (WACT)]


[http://www.phpwact.org/pattern/command Web Application Component Toolkit]
[http://www.phpwact.org/pattern/command Web Application Component Toolkit]
The Web Application Component Toolkit is a framework for creating web applications. WACT facilitates a modular approach where individual, independent or reusable components may be integrated into a larger web application. WACT assists in implementing the Model View Controller pattern and the related Domain Model, Template View, Front Controller and Application Controller patterns. WACT emphasizes writing secure web applications.   
The Web Application Component Toolkit is a framework for creating web applications. WACT facilitates a modular approach where individual, independent or reusable components may be integrated into a larger web application. WACT assists in implementing the Model View Controller pattern and the related Domain Model, Template View, Front Controller and Application Controller patterns. WACT emphasizes writing secure web applications.   
 
<br>
 
<b>WACT sees Command Pattern as</b>
 
 
WACT sees Command Pattern as
A GoF Design Pattern with the intent: “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”
A GoF Design Pattern with the intent: “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”


In WACT, this is seen with the FormController, where users can define a class which must contain the method performAction();
In WACT, this is seen with the FormController, where users can define a class which must contain the method performAction();


<pre>
class AddressForm extends PostFormController {
class AddressForm extends PostFormController {
   
   
Line 134: Line 136:
   
   
}
}
</pre>


The FormController expects to find the performAction method in the Action Class RegisterUser, calling it when the form is submitted (and successfully validated).
The FormController expects to find the performAction method in the Action Class RegisterUser, calling it when the form is submitted (and successfully validated).
Line 139: Line 142:
The Command pattern is a Gang of Four Design Pattern, used to allow a function name to be wrapped up in a class namespace, so that some code, which will call the function, can be given an instance of one of many classes without caring which which instance it’s dealing with.
The Command pattern is a Gang of Four Design Pattern, used to allow a function name to be wrapped up in a class namespace, so that some code, which will call the function, can be given an instance of one of many classes without caring which which instance it’s dealing with.


Learning:
<b>Learning:</b><br>
Here the Form controller in its post functionality exhibits command pattern as it requires the object that calls the post form functionality to implement performAction method, the actions that the object needs to perform when the form is submitted, but the post form controller doesn't know what are actions performed by the performAction method and whose performAction  method is called all it requires is it needs a class that has the performAction method to post it forms.  
Here the Form controller in its post functionality exhibits command pattern as it requires the object that calls the post form functionality to implement performAction method, the actions that the object needs to perform when the form is submitted, but the post form controller doesn't know what are actions performed by the performAction method and whose performAction  method is called all it requires is it needs a class that has the performAction method to post it forms.  
Hence the performAction acts like a command that is being called whenever the form is posted.
Hence the performAction acts like a command that is being called whenever the form is posted.




Another Example:
<b>Another Example:</b>
<pre>
PHP example  
PHP example  
<?php
<?php
Line 173: Line 177:
}
}
?>
?>
 
</pre>
In the PHP example provided above, class Bold, Italic works on the function render.
In the PHP example provided above, class Bold, Italic works on the function render.


In class Tag, all it does is for each command in the command object, render functionality is called, the render doesn't know which command, bold or italics is called and what doesn't knows the functionality of command (bold or italics)  
In class Tag, all it does is for each command in the command object, render functionality is called, the render doesn't know which command, bold or italics is called and what doesn't knows the functionality of command (bold or italics)  


Applications
<b>Applications</b>


The Command pattern is used widely on in web based application frameworks like Java Struts from a PHP Perspective, usually in Action Classes, to allow framework users to define logic which responds to “events” in the application. Action Classes can be regarded as the “verbs” of the framework - they act on things - they do things.
The Command pattern is used widely on in web based application frameworks like Java Struts from a PHP Perspective, usually in Action Classes, to allow framework users to define logic which responds to “events” in the application. Action Classes can be regarded as the “verbs” of the framework - they act on things - they do things.


 
<b>Comparison to similar patterns</b>
Comparison to similar patterns


Commands and Mementos have some similarity due to the fact they both work with an object's internal properties. The Command pattern keeps a record of changes to an object's state, and applies those changes in an ad-hoc fashion. A Memento also records changes to an object's state, and can restore that state at any time. The Chain of Responsibility pattern seems to handle processing in a similar manner to the Command, except it hands off processing to another process linearly unlike the Command pattern. An Interpreter pattern works in the example above because we are using language elements to determine which changes to apply at a given time.
Commands and Mementos have some similarity due to the fact they both work with an object's internal properties. The Command pattern keeps a record of changes to an object's state, and applies those changes in an ad-hoc fashion. A Memento also records changes to an object's state, and can restore that state at any time. The Chain of Responsibility pattern seems to handle processing in a similar manner to the Command, except it hands off processing to another process linearly unlike the Command pattern. An Interpreter pattern works in the example above because we are using language elements to determine which changes to apply at a given time.


Advantages:
<b>Advantages:</b>
 
Since the object that implements the command design doesn't know what function it does and what object it affects, as it acts like a black box, the implementation of the objects that is calling the black box can be changed and it can be implemented independently without affecting the flow of the program.
 
Hence command pattern gives a wide range of flexibility and sophisticated design features.
 


Disadvantages:
• Since the object that implements the command design doesn't know what function it does and what object it affects, as it acts like a black box, the implementation of the objects that is calling the black box can be changed and it can be implemented independently without affecting the flow of the program.


It complicates the application design. Every pattern complicates application design; they’re used because the benefits outweigh the cost. In fact, they should only be used when the benefits outweigh the costs.
• Hence command pattern gives a wide range of flexibility and sophisticated design features.
<b>Disadvantages:</b>


• It complicates the application design. Every pattern complicates application design; they’re used because the benefits outweigh the cost. In fact, they should only be used when the benefits outweigh the costs.


Command Pattern on Javaworld


http://www.javaworld.com/javatips/jw-javatip68.html?page=1
== [http://www.javaworld.com/javatips/jw-javatip68.html?page=1 Command Pattern on Javaworld] ==


According to Javaworld,
<b>According to Javaworld,</b>


The design patterns not only accelerate the design phase of an object-oriented (OO) project but also increase the productivity of the development team and quality of the software.  
The design patterns not only accelerate the design phase of an object-oriented (OO) project but also increase the productivity of the development team and quality of the software.  
Line 209: Line 208:
They describe a Command pattern as an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver.  
They describe a Command pattern as an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver.  


Sender -  invokes an operation
<pre>
Receiver - receives the request to execute a certain operation.  
Sender     -  invokes an operation
Receiver   - receives the request to execute a certain operation.  
Decoupling - the sender has no knowledge of the Receiver's interface
Decoupling - the sender has no knowledge of the Receiver's interface
Request - the command that is to be executed.  
Request   - the command that is to be executed.  
</pre>


Command pattern provides us flexibility as well as extensibility.
Command pattern provides us flexibility as well as extensibility.


The program discussed in the javaworld web directory is class Fan {
The program discussed in the javaworld web directory is  
<pre>
class Fan {
         public void startRotate() {
         public void startRotate() {
                 System.out.println("Fan is rotating");
                 System.out.println("Fan is rotating");
Line 302: Line 305:
}
}


</pre>
<b>Learning:</b>


Learning:
In the above example,
 
 
In the above example,
The class Fan has startRotate() and stopRotate() methods,the class Light has turnOn() and turnOff() methods.
The class Fan has startRotate() and stopRotate() methods,the class Light has turnOn() and turnOff() methods.
The catch here is startRotate of Fan and turnOn of Light is performed when the switch is turned on and stopRotate of Fan and turnOff of Light is performed when the switch in turned off.
The catch here is startRotate of Fan and turnOn of Light is performed when the switch is turned on and stopRotate of Fan and turnOff of Light is performed when the switch in turned off.


Keeping this real world catch, the class switch is created as a kind of interface for  
Keeping this real world catch, the class switch is created as a kind of interface for  
fan and light to work on it turn on and turn off requests.
fan and light to work on it turn on and turn off requests.


The switch has flipUp and flipDown methods which acts like command design implementation.
The switch has flipUp and flipDown methods which acts like command design implementation.
The switch doesn't know what action it performs on flipUp and flipDown and what object is affected when flipUp and flipDown is pressed.  
The switch doesn't know what action it performs on flipUp and flipDown and what object is affected when flipUp and flipDown is pressed.  


Hence flipUp and flipDown acts like a command without knowing what function it does and what object it affects, but eventually performing the required action. That is the beauty of command design.  
Hence flipUp and flipDown acts like a command without knowing what function it does and what object it affects, but eventually performing the required action. That is the beauty of command design.  
 
 


The Command pattern has the following advantages:
<b>The Command pattern has the following advantages:</b>
1. A command decouples the object that invokes the operation from the one that knows how to perform it.
1. A command decouples the object that invokes the operation from the one that knows how to perform it.
2. A command is a first-class object. It can be manipulated and extended like any other object.
2. A command is a first-class object. It can be manipulated and extended like any other object.
Line 326: Line 326:
4. It's easy to add new commands, because you don't have to change the existing classes.
4. It's easy to add new commands, because you don't have to change the existing classes.


== [http://www.oodesign.com/command-pattern.html Command pattern on Oodesign.com] ==
'''Topics covered:'''
The reason why using Command pattern, intent of command pattern, a UML diagram to explain the adapter pattern. The application and implementation of Command patterns are mentioned. Furthermore, it presents some really great examples and specific problems where command pattern becomes a good fit to use.
[[File:1.jpg]]
'''Learning:'''
“An object that contains a symbol, name or key that represents a list of commands, actions or keystrokes”-- definition of a macro. The command design pattern was given birth from this idea.
The implemantation of a simple Command pattern:
The classes participating in the pattern:
* Command - declares an interface for executign an operation
* ConcreteComand - extends the Command interface, implementing the Execute method by invoking the corresponding operations on Receiver
* Client - creates a ConcreteCommand object and sets its receiver
* Invoker - asks the command to carry out the request
* Receiver - knows how to perform the operations
== [http://coherence.oracle.com/display/INCUBATOR/Command+Pattern Command pattern on Oracle.com] ==
'''Topics covered:'''
This page provides an example implementation of the Command Pattern build on top of Coherence. A good UML diagram is given with truly detailed explenations. You can also find example source code from the link in the page.
'''Learning:'''
* The Command Pattern advocates that:
1. An action to be performed zero or more times at some point in the future should be represented as an object called aCommand.
2. All necessary parameters required to perform the said action, should be encapsulated as attributes with in the saidCommand object.
3. The Command object must provide a mechanism to perform the action (typically represented an execute method defined on the said Command object)
* Command Pattern Usage Walkthrough: clearly shows how to use Command Pattern ( you will benefit a lot from it! )
== [https://www.informit.com/guides/content.aspx?g=java&seqNum=481 Command pattern on Informit.com] ==
'''Topics covered:'''
This page mainly talks about the responsibilities of different roles in Command Pattern. It gives us a simple example of using Command Pattern -- with complete code and detailed comments. It is really suitable for those who are new to this pattern.
'''Learning:'''
* Three roles defined in Command Pattern:
1. Client -- is responsible for creating the command and initializing it
2. Invoker -- is responsible for determining when a command should be executed


3. Receiver -- is an instance of the class that receives the action of the command


* Source code for a simple game that contains a game board, commands for moving up and down the game board, and a game that drives everything.
1. GameBoard.java  /*the receiver ,represents a game board*/


2. Command.java  /*the command interface*/


3. MoveUpCommand.java  /*command that moves the player up one space*/


4. MoveDownCommand.java  /*command that moves the player up down space*/


5. Game.java  /*invoker class*/


= Further readings =
*[http://blog.8thlight.com/micah-martin/2006/09/07/delegates-vs-command-pattern.html  Delegates Vs Command Pattern]
*[http://www.se.rit.edu/~se362/Misc/TypicalAreasForImprovement.html Typical Areas for Improvemen of the Design and its Documentation ( Pattern misuse )]
*[http://www.slideshare.net/jonsimon2/command-and-adapter-pattern Command pattern and Adapter pattern]
*[http://www.drdobbs.com/multithreaded-programming-with-the-comma/184416612 Multithreaded Programming with the Command Pattern]


References
= <b>References</b> =
http://www.itsmedia.ca/the-command-pattern-and-restful-interfaces/
<br>http://www.itsmedia.ca/the-command-pattern-and-restful-interfaces/
http://i.msdn.microsoft.com/cc163920.fig02(en-us).gif
<br>http://i.msdn.microsoft.com/cc163920.fig02(en-us).gif
http://www.codeproject.com/Articles/12263/The-Command-Pattern-and-MVC-Architecture
<br>http://www.codeproject.com/Articles/12263/The-Command-Pattern-and-MVC-Architecture
http://www.phpwact.org/
<br>http://www.phpwact.org/
http://www.phpwact.org/pattern/command
<br>http://www.phpwact.org/pattern/command
http://www.javaworld.com/javatips/jw-javatip68.html?page=1
<br>http://www.javaworld.com/javatips/jw-javatip68.html?page=1
http://en.wikipedia.org/wiki/Command_pattern
<br>http://en.wikipedia.org/wiki/Command_pattern
http://upload.wikimedia.org/wikipedia/commons/8/8e/Command_Design_Pattern_Class_Diagram.png
<br>http://upload.wikimedia.org/wikipedia/commons/8/8e/Command_Design_Pattern_Class_Diagram.png
http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/patexamples.html
<br>http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/patexamples.html
http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/pateximg14.gif
<br>http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/pateximg14.gif
<br>http://www.oodesign.com/command-pattern.html
<br>http://coherence.oracle.com/display/INCUBATOR/Command+Pattern
<br>https://www.informit.com/guides/content.aspx?g=java&seqNum=481
<br>http://dotnetslackers.com/articles/designpatterns/The-Command-Pattern.aspx
<br>http://blackwasp.co.uk/Command.aspx

Latest revision as of 03:46, 20 November 2012

Command Pattern

Adapter Pattern, a directory of sites

This wiki page provides a directory of sites for Command Design Pattern that will help readers to know what each website contains, why should readers refer one website over another and a list of examples that readers can look up to understand the Command Pattern.

Introduction

Definition:

The command pattern is a behavioural design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

Three terms always associated with the command pattern are client, invoker and receiver.

Client
The client instantiates the command object and provides the information required to call the method at a later time.
Invoker
The invoker decides when the method should be called.
Receiver
The receiver is an instance of the class that contains the method's code.
How does it works?

Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the owner of the method or the method parameters.

Command Real world Example

The Command pattern allows requests to be encapsulated as objects, thereby allowing clients to be parameterized with different requests. The "check" at a diner is an example of a Command pattern. The waiter or waitress takes an order, or command from a customer, and encapsulates that order by writing it on the check. The order is then queued for a short order cook. Note that the pad of "checks" used by different diners is not dependent on the menu, and therefore they can support commands to cook many different items.

When Would I Use This Pattern?
The Command Pattern is useful when:
• A history of requests is needed
• You need callback functionality
• Requests need to be handled at variant times or in variant orders
• The invoker should be decoupled from the object handling the invocation.
You'll see command being used a lot when you need to have multiple undo operations, where a stack of the recently executed commands are maintained. To implement the undo, all you need to do is get the last Command in the stack and execute it's undo() method. You'll also find Command useful for wizards, progress bars, GUI buttons and menu actions, and other transactional behavior.

Directory of sites

Command pattern on MSDN Microsoft Website

Command Pattern to -Simplify Distributed System Design Using the Command Pattern, MSMQ, and .NET

Object-based collaboration VS service-based collaboration

• Communication or exchange of request and service and the format or the pattern based on play an important criteria in successful implementation of object-based collaboration and service-oriented architecture.
• Systems generally share a common platform, allowing you to optimize in ways you can't on widely dispersed -systems that span various operating systems and development environments are preferred to follow object-based collaboration than service-based collaboration.
• But generally the participants are hybrid and they don't share a common platform, in such situations service oriented architecture comes handy. Here the requests are queued in Microsoft Message Queuing (MSMQ) which implements Command design pattern.

The distributed command system discussed here is the combination of reliable messaging, services, and the Command pattern. While most often seen as a design pattern for implementing desktop application menu systems, the Command pattern offers advantages for distributed systems when combined with a robust messaging infrastructure like MSMQ.

Learning:

The concept is very simple, in service oriented architecture, the participants don't share a common platform, hence you need a mechanism, a design pattern, a module to issue requests to objects.
The module that is doing the requesting doesn’t know what the receiver will be, or what operation will be requested.

Pattern and Participants

Class	              Description
Command	              Abstract base class for all Command objects
Concrete command      Any number of classes derived from Command
Client	              The creator of a command
Invoker	              Executes a command
Receiver	      Any class that is acted on by a command


Another Example:

In ASP.NET, the database communication are based on the commands, the database commands such as create connection, command statement, parameter doesn't know what the object is and what the object it is requesting and these are typical example of command design pattern it best.
Conclusion

The Command pattern specifies a set of interactions that you can apply to the development of distributed systems in .NET. Use this pattern in your application to implement a high-performance, extendable backbone connecting your near link nodes that run .NET-enabled operating systems to achieve optimal performance and rapid development. Distributed commands are a mix of classic object orientation, messaging, and service architecture that together fill a definite need in the distributed systems space.

Advantages

The benefit of the Command class is that it makes it easier to add new functions to an application. If we add a new capability, we no longer need to reopen the Controller class to code routing information. Instead, we encapsulate the information in a Command object and assign it to whatever control we use in the View to invoke the new capability. When the Command gets passed to the Controller, the Controller can use it to route the request, without knowing anything about it.

Disadvantages:
The major disadvantage of the pattern is that it results in lots of little Command classes that can clutter up a design.
The routing information that Command objects encapsulate has to go somewhere. If this information is not contained in Command objects, then it will have to go into the Controller.
The resulting bloat may necessitate partitioning the Controller into a subsystem, and it will certainly make the Controller harder to understand and maintain.

Command Pattern on Web Application Component Toolkit (WACT)

Web Application Component Toolkit The Web Application Component Toolkit is a framework for creating web applications. WACT facilitates a modular approach where individual, independent or reusable components may be integrated into a larger web application. WACT assists in implementing the Model View Controller pattern and the related Domain Model, Template View, Front Controller and Application Controller patterns. WACT emphasizes writing secure web applications.
WACT sees Command Pattern as A GoF Design Pattern with the intent: “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”

In WACT, this is seen with the FormController, where users can define a class which must contain the method performAction();

class AddressForm extends PostFormController {
 
    // Code omitted
 
    function InitializeActions() {
        $this->registerSubmitAction("register", "RegisterUser", PRE_VALID);
        $this->registerDefaultSubmitAction("RegisterUser", PRE_VALID);
    }
 
    // Code omitted
}

The registerSubmitAction call above points the controller at the class RegisterUser, which is where the Command pattern resides.


class RegisterUser {
 
    function performAction(&$context) {
        $DataSpace =& $context->getDataSpace();
        $Page =& new Template('/input/thanks.html');
        $Page->import($DataSpace->export());
        $Page->display();
        return FORM_COMPLETE;
    }
 
}

The FormController expects to find the performAction method in the Action Class RegisterUser, calling it when the form is submitted (and successfully validated).

The Command pattern is a Gang of Four Design Pattern, used to allow a function name to be wrapped up in a class namespace, so that some code, which will call the function, can be given an instance of one of many classes without caring which which instance it’s dealing with.

Learning:
Here the Form controller in its post functionality exhibits command pattern as it requires the object that calls the post form functionality to implement performAction method, the actions that the object needs to perform when the form is submitted, but the post form controller doesn't know what are actions performed by the performAction method and whose performAction method is called all it requires is it needs a class that has the performAction method to post it forms. Hence the performAction acts like a command that is being called whenever the form is posted.


Another Example:

PHP example 
<?php
/* interface */ class Tag {
   // The abstract command method
   function render($content);
}
 
class Bold {
   function render($content) {
       return "<b>$content</b>";
   }
}
 
class Italic {
   function render($content) {
       return "<i>$content</i>";
   }
}
 
$commands = array (
    new Bold(),new Italic(), new Italic(), new Bold()
);
 
// Iterate over the command objects
foreach ( $commands as $command ) {
    echo ( $command->render('Hello World!') );
}
?>

In the PHP example provided above, class Bold, Italic works on the function render.

In class Tag, all it does is for each command in the command object, render functionality is called, the render doesn't know which command, bold or italics is called and what doesn't knows the functionality of command (bold or italics)

Applications

The Command pattern is used widely on in web based application frameworks like Java Struts from a PHP Perspective, usually in Action Classes, to allow framework users to define logic which responds to “events” in the application. Action Classes can be regarded as the “verbs” of the framework - they act on things - they do things.

Comparison to similar patterns

Commands and Mementos have some similarity due to the fact they both work with an object's internal properties. The Command pattern keeps a record of changes to an object's state, and applies those changes in an ad-hoc fashion. A Memento also records changes to an object's state, and can restore that state at any time. The Chain of Responsibility pattern seems to handle processing in a similar manner to the Command, except it hands off processing to another process linearly unlike the Command pattern. An Interpreter pattern works in the example above because we are using language elements to determine which changes to apply at a given time.

Advantages:

• Since the object that implements the command design doesn't know what function it does and what object it affects, as it acts like a black box, the implementation of the objects that is calling the black box can be changed and it can be implemented independently without affecting the flow of the program.

• Hence command pattern gives a wide range of flexibility and sophisticated design features. Disadvantages:

• It complicates the application design. Every pattern complicates application design; they’re used because the benefits outweigh the cost. In fact, they should only be used when the benefits outweigh the costs.


Command Pattern on Javaworld

According to Javaworld,

The design patterns not only accelerate the design phase of an object-oriented (OO) project but also increase the productivity of the development team and quality of the software.

They describe a Command pattern as an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver.

Sender     -  invokes an operation
Receiver   - receives the request to execute a certain operation. 
Decoupling - the sender has no knowledge of the Receiver's interface
Request    - the command that is to be executed. 

Command pattern provides us flexibility as well as extensibility.

The program discussed in the javaworld web directory is

class Fan {
        public void startRotate() {
                System.out.println("Fan is rotating");
        }
        public void stopRotate() {
                System.out.println("Fan is not rotating");
        }
}
class Light {
        public void turnOn( ) {
                System.out.println("Light is on ");
        }
        public void turnOff( ) {
                System.out.println("Light is off");
        }
}
class Switch {
        private Command UpCommand, DownCommand;
        public Switch( Command Up, Command Down) {
                UpCommand = Up; // concrete Command registers itself with the invoker 
                DownCommand = Down;
        }
        void flipUp( ) { // invoker calls back concrete Command, which executes the Command on the receiver 
                        UpCommand . execute ( ) ;                           
        }
        void flipDown( ) {
                        DownCommand . execute ( );
        }
}
class LightOnCommand implements Command {
        private Light myLight;
        public LightOnCommand ( Light L) {
                myLight  =  L;
        }
        public void execute( ) {
                myLight . turnOn( );
        }
}
class LightOffCommand implements Command {
        private Light myLight;
        public LightOffCommand ( Light L) {
                myLight  =  L;
        }
        public void execute( ) {
                myLight . turnOff( );
        }
}
class FanOnCommand implements Command {
        private Fan myFan;
        public FanOnCommand ( Fan F) {
                myFan  =  F;
        }
        public void execute( ) {
                myFan . startRotate( );
        }
}
class FanOffCommand implements Command {
        private Fan myFan;
        public FanOffCommand ( Fan F) {
                myFan  =  F;
        }
        public void execute( ) {
                myFan . stopRotate( );
        }
}
public class TestCommand {
                public static void main(String[] args) {
                        Light  testLight = new Light( );
                        LightOnCommand testLOC = new LightOnCommand(testLight);
                        LightOffCommand testLFC = new LightOffCommand(testLight);
                        Switch testSwitch = new Switch( testLOC,testLFC);       
                        testSwitch.flipUp( );
                        testSwitch.flipDown( );
                        Fan testFan = new Fan( );
                        FanOnCommand foc = new FanOnCommand(testFan);
                        FanOffCommand ffc = new FanOffCommand(testFan);
                        Switch ts = new Switch( foc,ffc);
                        ts.flipUp( );
                        ts.flipDown( ); 
                }
}               
Command.java
public interface Command {
        public abstract void execute ( );
}

Learning:

• In the above example, The class Fan has startRotate() and stopRotate() methods,the class Light has turnOn() and turnOff() methods. The catch here is startRotate of Fan and turnOn of Light is performed when the switch is turned on and stopRotate of Fan and turnOff of Light is performed when the switch in turned off.

• Keeping this real world catch, the class switch is created as a kind of interface for fan and light to work on it turn on and turn off requests.

• The switch has flipUp and flipDown methods which acts like command design implementation. The switch doesn't know what action it performs on flipUp and flipDown and what object is affected when flipUp and flipDown is pressed.

• Hence flipUp and flipDown acts like a command without knowing what function it does and what object it affects, but eventually performing the required action. That is the beauty of command design.

The Command pattern has the following advantages: 1. A command decouples the object that invokes the operation from the one that knows how to perform it. 2. A command is a first-class object. It can be manipulated and extended like any other object. 3. Commands can be assembled into a composite command. 4. It's easy to add new commands, because you don't have to change the existing classes.

Command pattern on Oodesign.com

Topics covered: The reason why using Command pattern, intent of command pattern, a UML diagram to explain the adapter pattern. The application and implementation of Command patterns are mentioned. Furthermore, it presents some really great examples and specific problems where command pattern becomes a good fit to use.

Learning: “An object that contains a symbol, name or key that represents a list of commands, actions or keystrokes”-- definition of a macro. The command design pattern was given birth from this idea. The implemantation of a simple Command pattern:

The classes participating in the pattern:

  • Command - declares an interface for executign an operation
  • ConcreteComand - extends the Command interface, implementing the Execute method by invoking the corresponding operations on Receiver
  • Client - creates a ConcreteCommand object and sets its receiver
  • Invoker - asks the command to carry out the request
  • Receiver - knows how to perform the operations

Command pattern on Oracle.com

Topics covered: This page provides an example implementation of the Command Pattern build on top of Coherence. A good UML diagram is given with truly detailed explenations. You can also find example source code from the link in the page.

Learning:

  • The Command Pattern advocates that:

1. An action to be performed zero or more times at some point in the future should be represented as an object called aCommand. 2. All necessary parameters required to perform the said action, should be encapsulated as attributes with in the saidCommand object. 3. The Command object must provide a mechanism to perform the action (typically represented an execute method defined on the said Command object)

  • Command Pattern Usage Walkthrough: clearly shows how to use Command Pattern ( you will benefit a lot from it! )

Command pattern on Informit.com

Topics covered: This page mainly talks about the responsibilities of different roles in Command Pattern. It gives us a simple example of using Command Pattern -- with complete code and detailed comments. It is really suitable for those who are new to this pattern.

Learning:

  • Three roles defined in Command Pattern:

1. Client -- is responsible for creating the command and initializing it

2. Invoker -- is responsible for determining when a command should be executed

3. Receiver -- is an instance of the class that receives the action of the command

  • Source code for a simple game that contains a game board, commands for moving up and down the game board, and a game that drives everything.

1. GameBoard.java /*the receiver ,represents a game board*/

2. Command.java /*the command interface*/

3. MoveUpCommand.java /*command that moves the player up one space*/

4. MoveDownCommand.java /*command that moves the player up down space*/

5. Game.java /*invoker class*/

Further readings

References


http://www.itsmedia.ca/the-command-pattern-and-restful-interfaces/
http://i.msdn.microsoft.com/cc163920.fig02(en-us).gif
http://www.codeproject.com/Articles/12263/The-Command-Pattern-and-MVC-Architecture
http://www.phpwact.org/
http://www.phpwact.org/pattern/command
http://www.javaworld.com/javatips/jw-javatip68.html?page=1
http://en.wikipedia.org/wiki/Command_pattern
http://upload.wikimedia.org/wikipedia/commons/8/8e/Command_Design_Pattern_Class_Diagram.png
http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/patexamples.html
http://www.cours.polymtl.ca/inf3700/divers/nonSoftwareExample/pateximg14.gif
http://www.oodesign.com/command-pattern.html
http://coherence.oracle.com/display/INCUBATOR/Command+Pattern
https://www.informit.com/guides/content.aspx?g=java&seqNum=481
http://dotnetslackers.com/articles/designpatterns/The-Command-Pattern.aspx
http://blackwasp.co.uk/Command.aspx