This is a very simple pattern. It simply is an object that does a command. It is defined by an Interface with a run() method like this:
'Class Module Command
' To be used to Implement as an interface
Option Explicit
Public Sub run()
End Sub
An interface doesn’t get much simpler than this.
So how might we use it to good effect?
If we are creating other Classes that are going to do things, we can implement this interface and create another class to manage and initialize the commands. Here is an example of a class that implements Command:
'Class Module SendEmailCommand
Option Compare Database
Option Explicit
Implements Command
Private p_recipient As String
Private p_subject As String
Private p_body As String
Public Sub Init(recipient As String, subject As String, body As String)
p_recipient = recipient
p_subject = subject
p_body = body
End Sub
Private Sub Command_run()
' Code to send email
MsgBox "Sending email to " & p_recipient
End Sub
This next class would store and run the commands:
' Class Module CommandInvoker
Option Compare Database
Option Explicit
Private commands As Collection
Public Sub Init()
Set commands = New Collection
End Sub
Public Sub AddCommand(cmd As Command)
commands.Add cmd
End Sub
Public Sub ExecuteCommands()
Dim cmdIterator As Variant
Dim cmd As Command
For Each cmdIterator In commands
Set cmd = cmdIterator
cmd.run
Next cmdIterator
End Sub
And here is an example. You could batch emails to send, or group them as you wished. You could use code to schedule them to be sent at intervals like every 90 seconds. There are many possibilities.
' Command Pattern usage test added to a normal Module
Sub UseCommandPattern()
Dim invoker As New CommandInvoker
invoker.Init
Dim emailCommand As New SendEmailCommand
emailCommand.Init "[email protected]", "Subject", "Body"
invoker.AddCommand emailCommand
invoker.ExecuteCommands
End Sub
Other uses for the pattern might include maintaining a list of commands that have been executed in a user interface and implementing an undo / redo mechanism for the actions.