|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionApplying design patterns to practical software development is pretty interesting, and only when you attempt to apply can you grasp the merits described in textbooks. This article illustrates a case where I apply the Command Pattern to ASP.NET Menu controls. I also demonstrate the implementation of a generic command with Problem DescriptionAll ASP.NET Menu controls are most commonly applied to display the hyperlink structures (i.e. Site Map) of a Web site. However, you may want to use it to implement a scenario that after users click one of the menu items on the client-side, your program will react on the server-side according to the menu item clicked (e.g. protected void DefaultRadMenu_ItemClick(object sender, Telerik.Web.UI.RadMenuEventArgs e)
{
RadMenuItem selItem = e.Item;
if(selItem.Text == "Apple")
{
doApple();
}
else if(selItem.Text == "Orange")
{
doOrange();
}
else
{
// do something
}
}
Apply Command Pattern with Menu ControlsCommand pattern is a highly prevailing design pattern in OOP. If you are not familiar with it, please Google by yourself! In this article, Command pattern is designed with an interface public interface IMenuItemCommand
{
// Execute Command
void Execute();
// Describe the command
string Text { get; set;}
}
The protected void DefaultRadMenu_ItemClicked
(object sender, Telerik.Web.UI.RadMenuEventArgs e)
{
RadMenuItem selItem = e.Item;
IMenuItemCommand itemCmd = selItem.DataItem as IMenuItemCommand;
if (itemCmd != null)
{
itemCmd.Execute();
}
}
Notice that in order to let the preceding RadMenuItem item1 = new RadMenuItem("Hello");
item1.DataItem = new BaseMenuItemCommand (
delegate {
//do something on server-side;
});
RadMenu1.Items.Add(item1);
The above code snippet also demonstrates the use of the generic command, public void Execute()
{
if(ToDo != null)
{
ToDo();
}
}
…
private ToDoDelegate _toDo;
public ToDoDelegate ToDo
{
get { return _toDo; }
set { _toDo = value; }
}
public delegate void ToDoDelegate();
The purpose of In sum, applying the Command Pattern to Menu controls eliminates the “ ConclusionI hope this code sample could help you diminish the repetitive codes when you decide to employ Menu controls to implement the scenario described in this article. Although we specifically use History
|
|||||||||||||||||||||||||||||||||||