Last active
February 27, 2024 18:18
-
-
Save luishendrix92/991bb8a04f3c047e49a85a32810e5b2b to your computer and use it in GitHub Desktop.
OCaml Observer Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open Printf | |
(* Example adapted from the book: | |
Head First Design Patterns *) | |
class virtual observer = | |
object | |
method virtual update : unit | |
end | |
class ['o] subject = | |
object | |
val mutable observers : 'o list = [] | |
method attach o = observers <- o :: observers | |
method notify = List.iter (fun o -> o#update) observers | |
end | |
class ['o] weather_station = | |
object (self) | |
inherit ['o] subject | |
val mutable temperature = 27.75 | |
method get_temperature = temperature | |
method set_temperature temp = | |
temperature <- temp; | |
self#notify | |
end | |
class ['o] window_display station = | |
object | |
inherit observer | |
val station : 'o weather_station = station | |
method update = printf "Window Display: %f\n" station#get_temperature | |
end | |
class ['o] phone_display station = | |
object | |
inherit observer | |
val station : 'o weather_station = station | |
method update = printf "Phone Display: %f\n" station#get_temperature | |
end | |
let () = | |
let ws = new weather_station in | |
let window = new window_display ws in | |
let phone = new phone_display ws in | |
ws#attach window; | |
ws#attach phone; | |
ws#set_temperature 31.33; | |
ws#set_temperature 5.0 | |
;; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment