File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ type Message = {
2+ userId : string ;
3+ text : string ;
4+ } ;
5+
6+ type User = {
7+ id : number ;
8+ name : string ;
9+ } ;
10+
11+ // Singleton pattern provides one global instance for a whole application
12+ class ChatRoom {
13+ private static instance : ChatRoom ;
14+
15+ static getInstance ( ) {
16+ if ( ! ChatRoom . instance ) {
17+ ChatRoom . instance = new ChatRoom ( ) ;
18+ }
19+
20+ return ChatRoom . instance ;
21+ }
22+
23+ private constructor (
24+ public users : User [ ] = [ ] ,
25+ public messages : Message [ ] = [ ]
26+ ) { }
27+
28+ addMember ( user : User ) {
29+ this . users . push ( user ) ;
30+ }
31+
32+ sendMessage ( message : Message ) {
33+ this . messages . push ( message ) ;
34+ }
35+ }
36+
37+ // new ChatRoom() will return an error because the constructor is private
38+ const chatRoom = ChatRoom . getInstance ( ) ;
39+
40+ // in other part of the application we could request the same instance
41+ const secondChatRoom = ChatRoom . getInstance ( ) ;
42+
43+ console . log ( secondChatRoom === chatRoom ) ; // true
You can’t perform that action at this time.
0 commit comments