New Series–Design Patterns Week 1

Feb 2014 comment: This has to be seriously verbose F# code but I’m leaving it unedited for posterity! 

I’ve had a break from blogging and coding, however time to play a bit more. My resolution is to master F Sharp and Design Patterns.

This week’s pattern is a simple way to have a commanding presence within your project.

As ever, this is just an example of how one might design this pattern within VB and F Sharp. First up, a Command Pattern implementation in F Sharp:

open System.IO
type ICommandListener =
    abstract member Execute : unit -> unit

type Application() =
    member x.OpenFile() = 
         printfn "[Application] OpenFile"
//Other Methods

type OpenFileCommand(app: Application) =  //implied constructor
    member x._app = app
    interface ICommandListener with
        member x.Execute() = 
         printfn "[OpenFileCommand] Execute"

type Widget(listener : ICommandListener) =
    member x._listener = listener
    member x.SendClick() = 
         printfn "[Widget] SendClick"

let main() = 
    let app = new Application()
    let cmd = new OpenFileCommand(app)    
    let w = new Widget(cmd)

//Simulate a button click
printfn "done"


VB For comparsion: `

Public Interface ICommandListener
    Sub Execute()
End Interface

Public Class OpenFileCommand
    Implements ICommandListener
    Private ReadOnly _app As Application

    Public Sub New(app As Application)
        _app = app
    End Sub

    Public Sub Execute() Implements ICommandListener.Execute
        Console.WriteLine("[OpenFileCommand] Execute")
    End Sub
End Class

Public Class Widget
    Private _listener As ICommandListener
    Public Sub SetListener(l As ICommandListener)
        _listener = l
    End Sub

    Public Sub SendClick()
        Console.WriteLine("[Widget] SendClick")
    End Sub
End Class

Public Class Application
    Public Sub OpenFile()
        Console.WriteLine("[Application] OpenFile")
    End Sub
    'Other Methods
End Class

Public Class Program
    Shared Sub Main()
        Dim app = New Application
        Dim cmd = New OpenFileCommand(app)
        Dim w = New Widget
        'Simulate a button click
    End Sub
End Class