Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » VB.NET » Command Pattern in VB.NET

Command Pattern in VB.NET

Command pattern encapsulates a request as an object and gives it a known public interface. Command Pattern ensures that every object receives its own commands and provides a decoupling between sender and receiver. A sender is an object that invokes an operation, and a receiver is an object that receives the request and acts on it.

Author Rank :
Page Views : 19380
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Command pattern encapsulates a request as an object and gives it a known public interface. Command Pattern ensures that every object receives its own commands and provides a decoupling between sender and receiver. A sender is an object that invokes an operation, and a receiver is an object that receives the request and acts on it.

Let us examine this pattern with the help of most commonly used electronic gadgets at home, a VCR, a DVD player and a Universal Remote to start and stop them.

Follow steps mentioned below to create an implementation of Command pattern in VB.NET:

Step 1: Command Interface

Create a Command interface with Execute method. All the concrete Command objects must provide implementation of Execute method, as it would be called to perform the requested operation.

//File Name : ICommand.vb
Imports System
Public Interface ICommand
Sub Execute()
End Interface 'ICommand

Step 2: Command Objects

Create Command objects implementing Command interface needed for this example. These objects would act as Receivers and execute requested functionality through Execute method. For this example, we will consider four command objects, namely DVDPlayCommand- command to play DVD, DVDStopCommand - command to stop DVD and similarly VCRPlayCommand- command to play VCR and VCRStopCommand- command to stop VCR.

//File Name : DVDPlayCommand.vb
Imports System
Public Class DVDPlayCommand
Implements ICommand 'ToDo: Add Implements Clauses for implementation methods of these interface(s)
Public Sub New()
End Sub 'New
Public Sub Execute()
Console.WriteLine("DVD Started.")
End Sub 'Execute
End Class 'DVDPlayCommand

//File Name : DVDStopCommand.vb
Imports System
Public Class DVDStopCommand
Implements ICommand 'ToDo: Add Implements Clauses for implementation methods of these interface(s)
Public Sub New()
End Sub 'New
Public Sub Execute()
Console.WriteLine("DVD Stopped.")
End Sub 'Execute
End Class 'DVDStopCommand

//File Name : VCRPlayCommand.vb
Imports System
Public Class VCRPlayCommand
Implements ICommand 'ToDo: Add Implements Clauses for implementation methods of these interface(s)
Public Sub New()
End Sub 'New
Public Sub Execute()
Console.WriteLine("VCR Started.")
End Sub 'Execute
End Class 'VCRPlayCommand

//File Name : VCRStopCommand.vb
Imports System
Public Class VCRStopCommand
Implements ICommand 'ToDo: Add Implements Clauses for implementation methods of these interface(s)
Public Sub New()
End Sub 'New
Public Sub Execute()
Console.WriteLine("VCR Stopped.")
End Sub 'Execute
nd Class 'VCRStopCommand

Step 3: The Invoker or Sender Object.

The invoker or Sender object is the one which invokes the requested functionality.

Create a Remote object, which would act as an invoker and would invoke operation requested by Client. This object has a method called Invoke, which takes an ICommand object as parameter and invokes its Execute method.

//File Name : Remote.vb
Imports System
Public Class Remote
Public Sub New()
End Sub 'New
Public Sub Invoke(ByVal cmd As ICommand)
Console.WriteLine("Invoking.......")
cmd.Execute()
End Sub 'Invoke
End Class 'Remote

Step 4: And the Client Object.

Create a Client object, which would instantiate a Remote object and all the commands client is interested in and then would pass them to Remote object to invoke those operations.

//File Name : Client.vb
Imports System
_
Public Class Client
Public Sub New()
End Sub 'New
'Entry point which delegates to C-style main Private Function
Public Overloads Shared Sub Main()
System.Environment.ExitCode = Main(System.Environment.GetCommandLineArgs())

End
Sub
Public Overloads Shared Function Main(ByVal args() As [String]) As Integer
'Instantiate the invoker object
Dim remote As New Remote
'Instantiate DVD related commands and pass them to invoker object
Dim dvdPlayCommand As New DVDPlayCommand
remote.Invoke(dvdPlayCommand)
Dim dvdStopCommand As New DVDStopCommand
remote.Invoke(dvdStopCommand)
'Instantiate VCR related commands and pass them to invoker object
Dim vcrPlayCommand As New VCRPlayCommand
remote.Invoke(vcrPlayCommand)
Dim vcrStopCommand As New VCRStopCommand
remote.Invoke(vcrStopCommand)
Return 0
End Function 'Main
End Class 'Client

Step 5

Compile all above programs as

vbc /recurse:*.vb.

Step 6

Run the program Client.exe to see the output in your console window.

Invoking.......
DVD Started.
Invoking.......
DVD Stopped.
Invoking.......
VCR Started.
Invoking.......
VCR Stopped.

In this example Remote act as an invoker as it invokes DVD or VCR related command request passed to it by the client. Objects beginning with DVD and VCR act as receiver objects and they know how to complete the request. Thus, we can say that Remote(Sender) object does not have any knowledge of the operation, it just invokes the implementation through Execute method. However Receivers know very well how to implement the requested operation (Start or Stop). Hence there is decoupling between Sender(Remote) and Receiver(DVD/VCR).

Usage

One of most common use of this pattern is with Menu Items of a GUI application. Different commands can be created to invoke different functionality by clicking on different menu items of the application.

Disclaimer

The above program is intended solely for learning purpose. Author will not be held responsible for any failure or damage caused due to any other usage.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rajesh VS
Rajesh V.S is a software engineer in the area of C/C++/JAVA for the last 5 years. Currently he is interested in core C# language. He is Sun Certified Java Programmer. His other area of interest includes Design Patterns and CORBA. He is also a writer of numerous articles for many technical Web sites.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.