Sunday, 30 June 2019

How to create Singleton Class in Typescript and use it

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.
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;
}
}
view raw Singleton.ts hosted with ❤ by GitHub
// 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
The First class is the one which provides the Singleton Implementation and the second one is the one which I imported and used to store the data.
Please leave comments if you have any questions.

No comments:

Post a Comment