Observer pattern

Observer pattern in F#

Copy Source
Copy Link
Tools:
 1: type Subject() = 
 2:     let mutable notify = fun _ -> ()
 3:     member this.Subscribe (notifyFunction) = 
 4:         let wrap f i = f(i); i
 5:         notify <- (wrap notifyFunction) >> notify
 6:     member this.Reset() = notify <- fun _ -> ()
 7:     member this.SomethingHappen(k) = 
 8:         notify k
 9: 
10: type ObserverA() =
11:     member this.NotifyMe(i) = printfn "notified A %A" i
12: type ObserverB() = 
13:     member this.NotifyMeB(i) = printfn "notified B %A" i
14: 
15: let observer() = 
16:     let a = ObserverA()
17:     let b = ObserverB()
18:     let subject = Subject()
19:     subject.Subscribe(a.NotifyMe)
20:     subject.Subscribe(b.NotifyMeB)
21:     subject.SomethingHappen("good")
22: 
type Subject =
  class
    new : unit -> Subject
    member Reset : unit -> unit
    member SomethingHappen : k:string -> unit
    member Subscribe : notifyFunction:(string -> unit) -> unit
  end

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

Full name: Snippet.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: Snippet.Subject.Reset
member Subject.SomethingHappen : k:string -> unit

Full name: Snippet.Subject.SomethingHappen
val k : string

  type: string
  implements: System.IComparable
  implements: System.ICloneable
  implements: System.IConvertible
  implements: System.IComparable<string>
  implements: seq<char>
  implements: System.Collections.IEnumerable
  implements: System.IEquatable<string>
type ObserverA =
  class
    new : unit -> ObserverA
    member NotifyMe : i:'a -> unit
  end

Full name: Snippet.ObserverA
val this : ObserverA
member ObserverA.NotifyMe : i:'a -> unit

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

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

Full name: Snippet.ObserverB
val this : ObserverB
member ObserverB.NotifyMeB : i:'a -> unit

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

Full name: Snippet.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

More information

Link: http://fssnip.net/7j
Posted: 2 years ago
Author: Tao Liu (website)
Tags: Design Patterns