CSC/ECE 517 Fall 2012/ch2b 2w45 pg

From Expertiza_Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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