How to implement Singleton Pattern (syntax)

Both .NET 4.0 and F# have Lazy, so I think you want

module MySingleton =
    let private x = Lazy.Create(fun() -> 42)
    let GetInstance() = x.Value

(where 42 might be a new WhateverType() or whatever the expensive initialization is).

http://msdn.microsoft.com/en-us/library/dd997286.aspx

(Commentary: It's 2010, and getting rare to have to explicitly deal with synchronization primitives; languages and libraries are encapsulating all the common patterns.)


Sorry to reanimate an old question, just wanted to point out that some might try to expose Instance in a public property, in which case the following piece of code might be useful:

// private constructor, just as any OO singleton
type public MyType private() =
  inherit SomeParent()

  static let mutable instance = lazy(new MyType())

  // Get the instance of the type
  static member Instance with get() = instance.Value

The question was how to implement the Singleton pattern, not how to implement the Lazy-Load pattern. A singleton can be implemented thread-safely in several ways, e.g.:

// Standard approach in F# 2.0: using an implicit constructor.
type Singleton private() =
    static let instance = new Singleton()
    static member Instance = instance

// Abbreviated approach in F# 3.0: using an implicit constructor with auto property.
type Singleton private() =
    static member val Instance = Singleton()

// Alternative example: When you have to use an explicit ctor,
// and also want to check instanciation upon each access of the property.

/// This type is intended for private use within Singleton only.
type private SyncRoot = class end

type Singleton =
    [<DefaultValue>]
    static val mutable private instance: Singleton

    private new() = { }

    static member Instance = 
        lock typeof<SyncRoot> (fun() ->
            if box Singleton.instance = null then
                Singleton.instance <- Singleton())
        Singleton.instance    

Edit
Added a simplified F# 2.0 example with private implicit ctor, and the example with explicit ctor now uses a separate private type as sync root. Thanks to kvb for the hints.

Edit 2 Added F# 3.0 auto property syntax.

Tags:

Singleton

F#