Singleton Pattern in TypeScript
A singleton class with pivate constructor to avoid instantiation with new from outside the singleton.
/**
* A Singleton
*/
class Singleton {
private static instance: Singleton;
/**
* The constructor is private to prevent instantiation with the 'new' operator.
*/
private constructor() {
if(Singleton.instance){
throw new Error("instantiation failed: Use Singleton.getInstance() instead of new");
}
}
/**
* The static method to get the instance. Is the instance not already created, create a new instance
*/
public static getInstance(): Singleton {
return Singleton.instance ?? (Singleton.instance = new Singleton());
}
/**
* A sample method
*/
public doThis() {
console.log("doThis() called");
return this;
}
/**
* Another sample method
*/
public doThat(par0: number) {
console.log(`doThat(${par0}) called`);
return this;
}
}
Create a instance and use it.
const singleton = Singleton.getInstance();
singleton.doThis();
singleton.doThat(42);
Create the instance and use the fluent API to call its methods.
Singleton.getInstance()
.doThis()
.doThat(43);
Test if the created instance exists only once in the context.
const singleton2 = Singleton.getInstance();
assert(Object.is(singleton, singleton2)); // true
assert(Object.is(Singleton.getInstance(), singleton)); //true
Requires
| Tool | Version | See |
|---|---|---|
deno |
> 1.15.0 | Tools |