.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Command Objects

Posted By:Shashi Ray       Posted Date: February 26, 2009    Points: 15    Category: C#    URL: http://www.dotnetspark.com  

Command Objects


One way to ensure that every object receives its own commands directly is to use the Command pattern and create individual Command objects. A Command object always has an Execute() method that is called when an action occurs on that object. Most simply, a Command object implements at least the following interface.


public interface Command {

void Execute();



One objective of using this interface is to separate the user interface code from the actions the program must carry out, as shown here.


private void commandClick(object sender, EventArgs e) {

Command comd = (Command)sender;

comd.Execute ();



This event can be connected to every single user interface element that can be clicked, and each will contain its own implementation of the Execute method, by simply deriving a new clas from Button and Menuitem that supports this Command interface.


Then we can provide an Execute method for each object that carries out the desired action, thus keeping the knowledge of what to do inside the object where it belongs, instead of having another part of the program make these decisions.


One important purpose of the Command pattern is to keep the program and user interface objects completely separate from the actions that they initiate. In other words, these program objects should be completely separate from each other and should not have to know how other objects

work. The user interface receives a command and tells a Command object to carry out whatever duties it has been instructed to do. The UI does not and should not need to know what tasks will be executed. This decouples the UI class from the execution of specific commands, making it possible to modify or completely change the action code without changing the

classes containing the user interface.


The Command object can also be used when you need to tell the program to execute the command when the resources are available rather than immediately. In such cases, you are queuing commands to be executed later. Finally, you can use Command objects to remember operations so you can support Undo requests.


Shashi Ray

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend