CSC/ECE 517 Fall 2012/ch2b 2w45 pg

From PG_Wiki
Jump to: navigation, search


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.



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.

The client instantiates the command object and provides the information required to call the method at a later time.
The invoker decides when the method should be called.
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.



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.

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 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.

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');
        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.

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 
/* 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)


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.


• 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( ); 
public interface Command {
        public abstract void execute ( );


• 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

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. 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 pattern on

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.


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 on

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.


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

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

2. /*the command interface*/

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

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

5. /*invoker class*/

Further readings


Personal tools