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
Command Pattern UML

Revision number 2, Wednesday, July 23, 2008 11:24:46 AM by scott@elbandit.co.uk
You must Login to comment.
|
Fri, Aug 8, 2008 2:55 PM
by gregmac
|
You should use a List(of ICommand) instead of ArrayList - simpler, and avoids the need for CType()
|
|
Sat, Sep 13, 2008 3:11 AM
by gilfink
|
Nice written. You can read about the pattern and see a C# example in the following link: http://blogs.microsoft.co.il/blogs/gilf/archive/2008/06/23/command-pattern.aspx
|