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" //Implementation //Other Methods type OpenFileCommand(app: Application) = //implied constructor member x._app = app interface ICommandListener with member x.Execute() = printfn "[OpenFileCommand] Execute" x._app.OpenFile() type Widget(listener : ICommandListener) = member x._listener = listener member x.SendClick() = printfn "[Widget] SendClick" x._listener.Execute() let main() = let app = new Application() let cmd = new OpenFileCommand(app) let w = new Widget(cmd) //Simulate a button click w.SendClick() printfn "done" main()
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") _app.OpenFile() 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") _listener.Execute() 'Implementation End Sub End Class Public Class Application Public Sub OpenFile() 'Implementation 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 w.SetListener(cmd) 'Simulate a button click w.SendClick() End Sub End Class