Skip to content

Commit cccd3db

Browse files
authored
Merge pull request #4092 from luishendrix92/main
#23 - OCaml
2 parents 509a86f + 4b617fb commit cccd3db

File tree

1 file changed

+125
-0
lines changed

1 file changed

+125
-0
lines changed
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
open Printf
2+
3+
(******************************************************************************)
4+
(* *)
5+
(* The Singleton Pattern *)
6+
(* *)
7+
(* Singleton in terms of software design patterns, popularized by the *)
8+
(* 'gang of four' in the OOP sphere, is a class that can only have one *)
9+
(* instance in memory and can be shared everywhere in the project. *)
10+
(* This is very useful for stuff like resource pools, dependency injection, *)
11+
(* global state managers, and any situation in which no more than one *)
12+
(* instance of a class needs to be created. *)
13+
(* *)
14+
(* In an OOP language like Java, C# or C++, the way we implement this pa- *)
15+
(* ttern is by making the constructor private and instead exposing a method *)
16+
(* that will create the instance if it doesn't exist yet (NULL reference), *)
17+
(* or return the current instance otherwise. However, OCaml is a functional *)
18+
(* language, therefore we need to make use of module-level bindings combi- *)
19+
(* ned with the concet of a mutable reference or a record with mutable *)
20+
(* fields to simulate a global state variable that we can write and read *)
21+
(* to and from. Ideally we'd also need to make use of a Mutex. *)
22+
(* *)
23+
(* [ N O T E ] *)
24+
(* OCaml's built-in class syntax has no concept of a static members and *)
25+
(* private constructors so we can't make use of the [class] keyword here. *)
26+
(* *)
27+
(******************************************************************************)
28+
29+
module Singleton : sig
30+
val get_data : unit -> int
31+
val set_data : int -> unit
32+
end = struct
33+
let instance = ref 0
34+
let get_data () = !instance
35+
let set_data data = instance := data
36+
end
37+
38+
let _ =
39+
print_endline "Singleton module [Singleton] has a globally accessible";
40+
print_endline "value as a mutable reference, emulating a singleton in OOP!";
41+
print_newline ();
42+
printf "Current value: [%d] | Changing to [5]...\n" @@ Singleton.get_data ();
43+
Singleton.set_data 5;
44+
printf "New current value: [%d]\n" @@ Singleton.get_data ();
45+
print_newline ()
46+
;;
47+
48+
(*****************************************************************************)
49+
(* *)
50+
(* Dificultad Extra (Opcional) *)
51+
(* *)
52+
(* Utiliza el patrón de diseño "singleton" para representar una clase que *)
53+
(* haga referencia a la sesión de usuario de una aplicación ficticia. *)
54+
(* La sesión debe permitir asignar un usuario (id, username, nombre y e- *)
55+
(* mail), recuperar los datos del usuario y borrar los datos de la sesión. *)
56+
(* *)
57+
(*****************************************************************************)
58+
59+
module SessionManager : sig
60+
type session
61+
62+
val set_data : int -> string -> string -> string -> unit
63+
val get_data : unit -> session option
64+
val clear : unit -> unit
65+
val show : unit -> string
66+
end = struct
67+
type session =
68+
{ id : int
69+
; username : string
70+
; full_name : string
71+
; email : string
72+
}
73+
[@@deriving show { with_path = false }]
74+
75+
let data : session option ref = ref None
76+
77+
let set_data id username full_name email =
78+
data := Some { id; username; full_name; email }
79+
;;
80+
81+
let show () =
82+
match !data with
83+
| None -> "{ NO SESSION! }"
84+
| Some session -> show_session session
85+
;;
86+
87+
let get_data () = !data
88+
let clear () = data := None
89+
end
90+
91+
let _ =
92+
print_endline "Session management system:";
93+
print_endline "--------------------------";
94+
printf "Current session: %s\n" @@ SessionManager.show ();
95+
print_endline "Setting the session with a new user...";
96+
SessionManager.set_data
97+
2399
98+
"luishendrix92"
99+
"Luis Felipe Lopez Garay"
100+
"luishendrix92@gmail.com";
101+
printf "Current session: %s\n" @@ SessionManager.show ();
102+
print_endline "Deleting session data from a different thread...";
103+
Thread.create (fun () -> SessionManager.clear ()) () |> Thread.join;
104+
printf "Current session: %s\n" @@ SessionManager.show ()
105+
;;
106+
107+
(*
108+
Output
109+
===========================================================
110+
Singleton module [Singleton] has a globally accessible
111+
value as a mutable reference, emulating a singleton in OOP!
112+
113+
Current value: [0] | Changing to [5]...
114+
New current value: [5]
115+
116+
Session management system:
117+
--------------------------
118+
Current session: { NO SESSION! }
119+
Setting the session with a new user...
120+
Current session: { id = 2399; username = "luishendrix92";
121+
full_name = "Luis Felipe Lopez Garay"; email = "luishendrix92@gmail.com" }
122+
Deleting session data from a different thread...
123+
Current session: { NO SESSION! }
124+
===========================================================
125+
*)

0 commit comments

Comments
 (0)