Skip to content

Commit cf66040

Browse files
committed
feat(creational): add singleton pattern
0 parents commit cf66040

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

creational/singleton.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

0 commit comments

Comments
 (0)