-
Notifications
You must be signed in to change notification settings - Fork 1
/
sample1.ts
29 lines (24 loc) · 864 Bytes
/
sample1.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Implementation of singleton design pattern in typescript.
*
* Singleton is a creational design pattern that lets you
* ensure that a class has only one instance while providing
* a global access point to this instance
*/
class FileService {
private static _fileService: FileService = null;
private constructor() {}
public static getFileService() {
if (this._fileService === null) {
this._fileService = new FileService();
}
return this._fileService;
}
public readFileByUrl(url: string): void {
console.log('Opening ' + url + "...");
}
}
const fileService = FileService.getFileService();
fileService.readFileByUrl('MyFile');
const fileService2 = FileService.getFileService();
console.log(fileService === fileService2); // True, because both constants are the same instance.