65.9K
CodeProject is changing. Read more.
Home

Command Pattern

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 11, 2013

CPOL

1 min read

viewsIcon

6080

Command Pattern"Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and

Command Pattern

"Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. "

A VB example of the Command Pattern

A lot of the new multimedia keyboards have extra buttons on them for opening up a web browser, an mp3 player etc. we can use the Command pattern to program them so that the keybaord need not know what application it is executing.

' This is the Invoker
Public Class MultiMediaKeyBoard

     
' This array holds commands for the buttons
    
' of our keyboard
    
Private _ButtonSlots As New ArrayList(2)     

     Public
Sub Main()
        
' Set up the commands to corresponding keyboard
        
' buttons.
        
Dim aWebBrowser As New WebBrowser
         _ButtonSlots(0) =
New WebBrowserCommand(aWebBrowser)

         Dim aWordProcessor As New WordProcessor
         _ButtonSlots(1) =
New WordProcessorCommand(aWordProcessor)

     
End Sub

      Public Sub MediaButtonPushed(ByVal buttonNumber As Integer)

          
' When a button is clicked on the keyboard its API can send us the
         
' buttons ID. We can then call the execute method of the class in the
         
' corresponding
         
CType(_ButtonSlots(buttonNumber), ICommand).execute()

     
End Sub

End
Class

Public Interface ICommand
  
Sub execute()
End Interface

' The receiver
Public Class WebBrowser

      Public Sub OpenWebBrowser()
         
' Code to open a web browser
     
End Sub
End Class

' The concrete command class
Public Class WebBrowserCommand
     
Implements ICommand

     
Private _WebBrowser As WebBrowser
   
     
Public Sub New(ByVal WebBrowser As WebBrowser)
            _WebBrowser = WebBrowser
      
End Sub      

      Public
Sub execute() Implements ICommand.execute
           _WebBrowser.OpenWebBrowser()
     
End Sub

End Class

' The receiver
Public Class WordProcessor

     
Public Sub OpenWordProcessor()
          
' Code to open a word processor
     
End Sub
End Class

' The concrete command class
Public Class WordProcessorCommand
     
Implements ICommand

      Private _WordProcessor As WordProcessor

     
Public Sub New(ByVal WordProcessor As WordProcessor)
           _WordProcessor = WordProcessor
     
End Sub

      Public Sub execute() Implements ICommand.execute
           _WordProcessor.OpenWordProcessor()
     
End Sub

End Class