如何使用 F# 中的单例模式更新具有记录成员的类

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

假设我有这个记录定义:

type WindowServices =
    {
        ReportMenu: Window option 
        ProgressNotes: Window option
        PatientRegistration: Window option
    }

此外,我在这个类中尝试实现单例模式:

type WindowServiceManager private(wss) =  
    let mutable ws:WindowServices = wss  
    member this.WS 
        with get () = ws
        and set (value) = ws <- value
    
    static member val Instance = 
            let wss = {ReportMenu = None; ProgressNotes = None; PatientRegistration = None}    
            WindowServiceManager(wss)

在课堂之外,单例“Instance”似乎可以通过以下方式正确获得:

let i = WindowServiceManager.Instance

但是,绝对nothing我试过可以更改默认记录值。也就是说,这失败了。 “windowServices”中的新值永远不会输入到 WS:

let windowServices : WindowServices = 
              { ReportMenu = Some  reportMenu; 
                ProgressNotes = Some progressNoteWindow; 
                PatientRegistration = Some patientRegistrationWindow }
           
i.WS <- windowServices

这是怎么做到的?

TIA

附录:以下显示失败。 “failwith”是总是命中:

let getReportMenuService : Window = 
    let i = WindowServiceManager.Instance
    let p = match i.WS.ReportMenu with
        | None -> failwith "[ReportMenuService] Something went wrong!"
        | Some s -> s
    p
f# singleton
1个回答
0
投票

我认为您的代码中还有一些您尚未与我们分享的内容。您提供的代码按预期工作(为简单起见,使用

Window
作为
string
的别名):

type Window = string

type WindowServices =
    {
        ReportMenu: Window option 
        ProgressNotes: Window option
        PatientRegistration: Window option
    }

type WindowServiceManager private(wss) =  
    let mutable ws:WindowServices = wss  
    member this.WS 
        with get () = ws
        and set (value) = ws <- value
    
    static member val Instance = 
            let wss = {ReportMenu = None; ProgressNotes = None; PatientRegistration = None}    
            WindowServiceManager(wss)

let i = WindowServiceManager.Instance

let windowServices : WindowServices = 
              { ReportMenu = Some "ReportMenu";
                ProgressNotes = Some "ProgressNotes" ;
                PatientRegistration = Some "PatientRegistration" }
           
i.WS <- windowServices

let getReportMenuService : Window = 
    let i = WindowServiceManager.Instance
    let p =
        match i.WS.ReportMenu with
        | None -> failwith "[ReportMenuService] Something went wrong!"
        | Some s -> s
    p

getReportMenuService
    |> printfn "%A"   // "ReportMenu"
© www.soinside.com 2019 - 2024. All rights reserved.