Command Design Pattern
Command Design Pattern
Free Online Articles Directory
Why Submit Articles?
Top Authors
Top Articles
FAQ
ABAnswers
0 && $.browser.msie ) {
var ie_version = parseInt($.browser.version);
if(ie_version Login
Register
Hello
My Home
Sign Out
Email
Password
Remember me?
Lost Password?
Home Page > Computers > Information Technology > Command Design Pattern
Command Design Pattern
Posted: Jul 25, 2008 |Comments: 0
| Views: 466 |
]]>
Command pattern is a separation of following paticipants to carry out some task:
Client – Who wants the task done (our program, like main(…) method)
Invoker - Who initiates a task
Receiver – Who listenes to the command and carries out the task.
Command - interface for execution between invoker and receiver.
ConcreteCommand – implementation of Command. Holds the parameters required to carry out the operation.
Now look at the code snippet below( taken from GOF http://www.dofactory.com/Patterns/PatternCommand.aspx)
// Command pattern — Real World example
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Command.RealWorld
{
// MainApp test application
class MainApp
{
static void Main()
{
// Create user and let her compute
User user = new User();
user.Compute(‘+’, 100);
user.Compute(‘-’, 50);
user.Compute(‘*’, 10);
user.Compute(‘/’, 2);
// Undo 4 commands
user.Undo(4);
// Redo 3 commands
user.Redo(3);
// Wait for user
Console.Read();
}
}
// “Command”
abstract class Command
{
public abstract void Execute();
public abstract void UnExecute();
}
// “ConcreteCommand”
class CalculatorCommand : Command
{
char @operator;
int operand;
Calculator calculator;
// Constructor
public CalculatorCommand(Calculator calculator,
char @operator, int operand)
{
this.calculator = calculator;
this.@operator = @operator;
this.operand = operand;
}
public char Operator
{
set{ @operator = value; }
}
public int Operand
{
set{ operand = value; }
}
public override void Execute()
{
calculator.Operation(@operator, operand);
}
public override void UnExecute()
{
calculator.Operation(Undo(@operator), operand);
}
// Private helper function
private char Undo(char @operator)
{
char undo;
switch(@operator)
{
case ‘+’: undo = ‘-’; break;
case ‘-’: undo = ‘+’; break;
case ‘*’: undo = ‘/’; break;
case ‘/’: undo = ‘*’; break;
default : undo = ‘ ‘; break;
}
return undo;
}
}
// “Receiver”
class Calculator
{
private int curr = 0;
public void Operation(char @operator, int operand)
{
switch(@operator)
{
case ‘+’: curr += operand; break;
case ‘-’: curr -= operand; break;
case ‘*’: curr *= operand; break;
case ‘/’: curr /= operand; break;
}
Console.WriteLine(
”Current value = {0,3} (following {1} {2})”,
curr, @operator, operand);
}
}
// “Invoker”
class User
{
// Initializers
private Calculator calculator = new Calculator();
private ArrayList commands = new ArrayList();
private int current = 0;
public void Redo(int levels)
{
Console.WriteLine(“n—- Redo {0} levels “, levels);
// Perform redo operations
for (int i = 0; i {
if (current {
Command command = commands[current++] as Command;
command.Execute();
}
}
}
public void Undo(int levels)
{
Console.WriteLine(“n—- Undo {0} levels “, levels);
// Perform undo operations
for (int i = 0; i {
if (current > 0)
{
Command command = commands[--current] as Command;
command.UnExecute();
}
}
}
public void Compute(char @operator, int operand)
{
// Create command operation and execute it
Command command = new CalculatorCommand(
calculator, @operator, operand);
command.Execute();
// Add command to undo list
commands.Add(command);
current++;
}
}
}
Here Main(…) is the client
Client asks User (Invoker) to carry out some task (Calculations by Compute(…) method)
User knows about Calculator (Receiver) who will do the calculation and command which is an interface to call the required calculation operation (Execute or Unexecute).
But what calculation is to be done is known to Client. Client asks (or issues commands) User to do some +, – , *, / operations.
User records these commands in an array and calls command.Execute or UnExecute. the implementation(CalculatorCommand) knows well how to do the opertaion.
* Now here comes the use of command. If there is need to undo upto some level, user has a record of what commands were issued. It will just call the receiver (CalculatorCommand) to carry out same commands in reverse.
Uses for the Command pattern
Command objects are useful for implementing:
Multi-level undo: If all user actions in a program are implemented as command objects, the program can keep a stack of the most recently executed commands. When the user wants to undo a command, the program simply pops the most recent command object and executes its undo() method.
Transactional behavior Undo is perhaps even more essential when it’s called rollback and happens automatically when an operation fails partway through. Installers need this and so do databases. Command objects can also be used to implement two-phase commit.
Progress bars Suppose a program has a sequence of commands that it executes in order. If each command object has a getEstimatedDuration() method, the program can easily estimate the total duration. It can show a progress bar that meaningfully reflects how close the program is to completing all the tasks.
Wizards Often a wizard presents several pages of configuration for a single action that happens only when the user clicks the “Finish” button on the last page. In these cases, a natural way to separate user interface code from application code is to implement the wizard using a command object. The command object is created when the wizard is first displayed. Each wizard page stores its GUI changes in the command object, so the object is populated as the user progresses. “Finish” simply triggers a call to execute(). This way, the command class contains no user interface code.
GUI buttons and menu items In Swing and Borland Delphi programming, an Action is a command object. In addition to the ability to perform the desired command, an Action may have an associated icon, keyboard shortcut, tooltip text, and so on. A toolbar button or menu item component may be completely initialized using only the Action object.
Thread pools A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. The items in the queue are command objects. Typically these objects implement a common interface such as java.lang.Runnable that allows the thread pool to execute the command even though the thread pool class itself was written without any knowledge of the specific tasks for which it would be used.
Macro recording If all user actions are represented by command objects, a program can record a sequence of actions simply by keeping a list of the command objects as they are executed. It can then “play back” the same actions by executing the same command objects again in sequence. If the program embeds a scripting engine, each command object can implement a toScript() method, and user actions can then be easily recorded as scripts.
Networking It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games.
Parallel Processing Where the commands are written as tasks to a shared resource and executed by many threads in parallel (possibly on remote machines -this variant is often referred to as the Master/Worker pattern)
Mobile Code Using languages such as Java where code can be streamed/slurped from one location to another via URLClassloaders and Codebases the commands can enable new behavior to be delivered to remote locations (EJB Command, Master Worker)
References:
GOF official site:
http://www.dofactory.com/Patterns/PatternCommand.aspx
Wikipidea
http://en.wikipedia.org/wiki/Command_pattern
Retrieved from “http://www.articlesbase.com/information-technology-articles/command-design-pattern-496567.html”
(ArticlesBase SC #496567)
Start increasing your traffic today just by submitting articles with us, click here to get started.
Liked this article? Click here to publish it on your website or blog, it’s free and easy!
Sandeep Bhutani -
About the Author:
Software developer in India
]]>
Questions and Answers
Ask our experts your Information Technology related questions here…
200 Characters left
What are the design patterns in .net ?
How many types of design patterns in java ?
What are the design patterns used in spring ?
Rate this Article
vote(s)
0 vote(s)
Feedback
RSS
Print
Email
Re-Publish
Source: http://www.articlesbase.com/information-technology-articles/command-design-pattern-496567.html
Article Tags:
design patterns, command pattern, computers, coding, architecture
Latest Information Technology Articles
Introducing Windows Server Foundation – FrugalTech
Looks like Microsoft Small Business Server has a new little brother. With server hardware available for less than 1K, its hard to justify paying 0 or more for the Server OS. Distributed by Tubemogul. (06:08)
How to Monitor a Mac from an iPhone
If you want to monitor your Mac from your iPhone it’s really easy to do. Just put iStat of iPhone on your iPhone and iStat Server for Max OS X on your Mac. You can see how much storage space is available, how much memory is used and free, even the temperature of your Mac’s CPU and other components. (02:06)
computer virus is a computer program that can copy itself and infect a computer without the permission or knowledge of the owner. The term “virus” is also commonly but erroneously used to refer to other types of malware, adware, and spyware programs that do not have the reproductive ability. A true virus can only spread ….
By:
stephenl
Computersl
Aug 12, 2009
lViews: 201
devolpment, of Computers and Technology
Computers in some form are in almost everything these days. From Toasters to Televisions, just about all electronic things has some form of processor in them. This is a very large change from the way it used to be, when a computer that would take up an entire room and weighed tons of pounds has the same amount of power as a scientific calculator. The changes that computers have undergone in the last 40 years have been colossal. So many things have changed from the ENIAC that had very little
By:
iTech Troubleshooterl
Computers>
E-Learningl
Nov 20, 2010
net interview preparation questions and answers
faq on .net interview preparation questions and answers its all about interview preparation for fresher to make them understand basic .net question
By:
gdrealspacel
Computers>
Programmingl
Nov 24, 2010
A neural network also known as an artificial neural network provides a unique computing architecture whose potential has only begun to be tapped. They are used to address problems that are intractable or cumbersome with traditional methods. These new computing architectures are radically different from the computers that are widely used today. ANN’s are massively parallel systems that rely on dense arrangements of interconnections and surprisingly simple processors (Cr95, Ga93).
By:
iTech Troubleshooterl
Computers>
Networksl
Nov 21, 2010
Java training have smaller sized execution time when compared with compiled types
A high-level Java training computer programming dialect designed by Sunrays Microsystems. Java was initially called OAK,
By:
Fresherlabl
Education>
Learning Disabilitiesl
Sep 27, 2010
A Survey on Botnets with Cryptography
As technology has been developed, the network of bot, botnet, has been huge matter in computer science society. Most botnet causes network security threats and they are based on C&C server such as IRC, HTTP common protocol [1] and recently botnet also constructs P2P connection and the bot’s characteristics and activities are all different according to the structure of botnet. That is why the existed research is numerous, too, and it is beneficial to categorize and to classify defense mechanism
By:
Satyavathyl
Computers>
Securityl
Oct 29, 2009
lViews: 498
Synonyms are words with similar meanings. However, it’s difficult to say which word has most number of synonyms because the synonyms of a particular word tend to be subjective and their meanings tend to vary from the original word.
By:
Mr. Ashok Sharmal
Arts & Entertainment>
Literature l
Jan 14, 2011
The Best Verizon iPhone 4 Cases
Recently, I detailed my Verizon iPhone pre-order experience. I wondered aloud whether it was really worth getting up at 3:00AM to order my new phone. After checking out some of the responses I got, I’m guessing it was the right thing to do.
By:
wholesaleeshopsl
Computers>
Information Technologyl
Feb 21, 2011
The iPad is Apple’s first tablet computer. In 2010, Apple announced its latest one and this iPad information had been highly awaited by many tech lovers and enthusiasts. A good number of them left feeling happy and several others left feeling quite disappointed.
By:
Timothyl
Computers>
Information Technologyl
Feb 21, 2011
It Is Easy To Convert Videos For iPad
For most iPad lovers, it is usually disappointing to realize that your tablet gadget only plays a limited number of video formats and these formats are not your usual size of videos. You will find a good number of torrents come as AVIs and you will need to convert videos for iPad otherwise you will not be able to enjoy the high definition quality when you find yourself having to change into an MP4 format or into any other format that is compatible.
By:
Timothyl
Computers>
Information Technologyl
Feb 21, 2011
If you have been a fan of all other previous ipads, then you are probably going to like the iPad two as well. There has been an anticipated introduction of a newer iPad and there have been some insider data that has been leaking into the market and the information keeps leaking out in bigger and bigger volumes.
By:
Timothyl
Computers>
Information Technologyl
Feb 21, 2011
Google Android application development
Google Android application development uses the Google Android operating system. The Google Android operating system is known for its intuitive design, support for multiple networks and the ability for framing various applications.
By:
Austin Maltbyl
Computers>
Information Technologyl
Feb 21, 2011
Why is Cloud Computing a Safe Bet for the Future?
All organizations are concerned about keeping costs under control and be as efficient as possible in their spending. Lately, there is a new shift in the IT world, focused on new lighter-weight technologies: cloud computing, Software as a Service and virtualization.
By:
Rickl
Computers>
Information Technologyl
Feb 21, 2011
Quantum Internet and Cybersecurity
Quantum computing has the potential to revolutionize the way that we use computers and the internet. Unlike traditional binary computing, in which bits must take the form of either a 0 or a 1, in quantum computing it is possible for Q-bits, as they are called, to take intermediate forms. A Q-bit can be both 0 and 1 at the same time. This increases the range of possibilities and enables quantum computing to be far more powerful than conventional computing.
Computers>
Information Technologyl
Feb 21, 2011
Reliable and Robust Web Development Solutions with Dot NET Technology
If you are interested in developing secure online platform for your customers, then look no further as .NET framework is available with web development companies to make it possible. Introduced in the year 2002, this latest software technology is a part of Microsoft windows Operating System.
By:
Odndl
Computers>
Information Technologyl
Feb 21, 2011
Add new Comment
Your Name: *
Your Email:
Comment Body: *
Verification code:*
* Required fields
Submit
Your Articles Here
It’s Free and easy
Sign Up Today
Author Navigation
My Home
Publish Article
View/Edit Articles
View/Edit Q&A
Edit your Account
Manage Authors
Statistics Page
Personal RSS Builder
My Home
Edit your Account
Update Profile
View/Edit Q&A
Publish Article
Author Box
Sandeep Bhutani has 1 articles online
Articles Categories
All Categories
Advertising
Arts & Entertainment
Automotive
Beauty
Business
Careers
Computers
Education
Finance
Food and Beverage
Health
Hobbies
Home and Family
Home Improvement
Internet
Law
Marketing
News and Society
Relationships
Self Improvement
Shopping
Spirituality
Sports and Fitness
Technology
Travel
Writing
Computer Forensics
Computer Games
Data Recovery
Databases
E-Learning
File Types
Hardware
Information Technology
Intra-net
Laptops
Networks
Operating Systems
Programming
Security
Software
]]>
Need Help?
Contact Us
FAQ
Submit Articles
Editorial Guidelines
Blog
Site Links
Recent Articles
Top Authors
Top Articles
Find Articles
Site Map
Mobile Version
Webmasters
RSS Builder
RSS
Link to Us
Business Info
Advertising
Use of this web site constitutes acceptance of the Terms Of Use and Privacy Policy | User published content is licensed under a Creative Commons License.
Copyright © 2005-2011 Free Articles by ArticlesBase.com, All rights reserved.
Software developer in India
2007 ‘Luminous Architectural Surveillance’ An interactive, responsive LED installation by Alex Haw (Atmos) at the Architectural Association in April/May 2007 – a form of 3d-cctv, or luminous architectural surveillance – that allowed immediate verification of presence throughout the building. LightHive is set to transform the Georgian splendour of the AA’s Front Members’ Room into a dynamic and immersive constellation, a gigantic lighthouse broadcasting the activity of the School through its enormous piano nobile windows to the world beyond. The geometry of the AA’s entire collection of real estate is compressed as a 1:5 model to fit into the exhibition space, the building represented purely by the light sources that enable it to function. The precise position, intensity, function and colour temperature of each and every fixture is co-located within this single room, the geometries of their original surroundings generating 2100 unique shapes that are custom designed, scripted and then lasercut especially for the show by Zumtobel. Each of the 160 cellular zones that compose the building is laced with a range of sensors, from door contacts to seat sensors, infar-red detectors to IP cameras, which are then wired back across the network to the luminous sky of the exhibition space. Activity triggers a signal to a central processing unit, activating one or more of the 1000 bespoke LED, spilling light into the room. The space thus operates like a three-dimensional x-ray of the …

