34 people like it.

Observer pattern

Observer pattern in F#

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
type Subject() = 
    let mutable notify = fun _ -> ()
    member this.Subscribe (notifyFunction) = 
        let wrap f i = f(i); i
        notify <- (wrap notifyFunction) >> notify
    member this.Reset() = notify <- fun _ -> ()
    member this.SomethingHappen(k) = 
        notify k

type ObserverA() =
    member this.NotifyMe(i) = printfn "notified A %A" i
type ObserverB() = 
    member this.NotifyMeB(i) = printfn "notified B %A" i

let observer() = 
    let a = ObserverA()
    let b = ObserverB()
    let subject = Subject()
    subject.Subscribe(a.NotifyMe)
    subject.Subscribe(b.NotifyMeB)
    subject.SomethingHappen("good")
Multiple items
type Subject =
  new : unit -> Subject
  member Reset : unit -> unit
  member SomethingHappen : k:string -> unit
  member Subscribe : notifyFunction:(string -> unit) -> unit

Full name: Script.Subject

--------------------
new : unit -> Subject
val mutable notify : (string -> unit)
val this : Subject
member Subject.Subscribe : notifyFunction:(string -> unit) -> unit

Full name: Script.Subject.Subscribe
val notifyFunction : (string -> unit)
val wrap : (('a -> unit) -> 'a -> 'a)
val f : ('a -> unit)
val i : 'a
member Subject.Reset : unit -> unit

Full name: Script.Subject.Reset
member Subject.SomethingHappen : k:string -> unit

Full name: Script.Subject.SomethingHappen
val k : string
Multiple items
type ObserverA =
  new : unit -> ObserverA
  member NotifyMe : i:'a -> unit

Full name: Script.ObserverA

--------------------
new : unit -> ObserverA
val this : ObserverA
member ObserverA.NotifyMe : i:'a -> unit

Full name: Script.ObserverA.NotifyMe
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
Multiple items
type ObserverB =
  new : unit -> ObserverB
  member NotifyMeB : i:'a -> unit

Full name: Script.ObserverB

--------------------
new : unit -> ObserverB
val this : ObserverB
member ObserverB.NotifyMeB : i:'a -> unit

Full name: Script.ObserverB.NotifyMeB
val observer : unit -> unit

Full name: Script.observer
val a : ObserverA
val b : ObserverB
val subject : Subject
member Subject.Subscribe : notifyFunction:(string -> unit) -> unit
member ObserverA.NotifyMe : i:'a -> unit
member ObserverB.NotifyMeB : i:'a -> unit
member Subject.SomethingHappen : k:string -> unit
Raw view New version

More information

Link:http://fssnip.net/7j
Posted:4 years ago
Author:Tao Liu
Tags: Design Patterns