Hi Everybody, Today I will show you all how to write a Singleton class in Typescript and use it in you applications.
Below are the classes which I created one consists of Singleton class and other one to import and use it.
Below are the classes which I created one consists of Singleton class and other one to import and use it.
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
export class Singleton { | |
private static instance: Singleton; | |
private _data: number; | |
private constructor() { } | |
static getInstance() { | |
if (!Singleton.instance) { | |
Singleton.instance = new Singleton(); | |
Singleton.instance._data = 0; | |
} | |
return Singleton.instance; | |
} | |
get data(): number { | |
return this._data; | |
} | |
set data(data) { | |
this._data = data; | |
} | |
} |
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
// Usage | |
import { Singleton } from "./Singleton"; | |
const singleInstance = Singleton.getInstance(); | |
singleInstance.data = 10; | |
console.log(singleInstance.data); | |
//creating second instance should return same | |
const singleInstance2 = Singleton.getInstance(); | |
console.log(singleInstance2.data); //will return 10 |
Please leave comments if you have any questions.
No comments:
Post a Comment