在 F# 中实现 ThreadStatic 单例

问题描述 投票:0回答:3

我正在学习 F#,想实现 ThreadStatic 单例。我正在使用我在类似问题中找到的内容:F# How to Implement Singleton Pattern (syntax)

使用以下代码,编译器会抱怨

The type 'MySingleton' does not have 'null' as a proper value

type MySingleton = 
    private new () = {}
    [<ThreadStatic>] [<DefaultValue>] static val mutable private instance:MySingleton
    static member Instance =
        match MySingleton.instance with
        | null -> MySingleton.instance <- new MySingleton()
        | _ -> ()
        MySingleton.instance

在这种情况下如何初始化实例?

f# singleton
3个回答
8
投票

我认为

[<ThreadStatic>]
会导致代码相当笨重,尤其是在 F# 中。有一些方法可以更简洁地做到这一点,例如,使用
ThreadLocal
:

open System.Threading

type MySingleton private () = 
  static let instance = new ThreadLocal<_>(fun () -> MySingleton())
  static member Instance = instance.Value

4
投票

另一个 F#y 解决方案是将实例存储为 选项

type MySingleton = 
    private new () = {}

    [<ThreadStatic; DefaultValue>]
    static val mutable private instance:Option<MySingleton>

    static member Instance =
        match MySingleton.instance with
        | None -> MySingleton.instance <- Some(new MySingleton())
        | _ -> ()

        MySingleton.instance.Value

3
投票

接近 Ramon 所说的,将

AllowNullLiteral
属性应用于类型(默认情况下,在 F# 中声明的类型不允许“null”作为正确值):

[<AllowNullLiteral>]
type MySingleton = 
    private new () = {}
    [<ThreadStatic>] [<DefaultValue>] static val mutable private instance:MySingleton
    static member Instance =
        match MySingleton.instance with
        | null -> MySingleton.instance <- new MySingleton()
        | _ -> ()
        MySingleton.instance
© www.soinside.com 2019 - 2024. All rights reserved.