Singleton is the most popular design pattern.
It is a kind of creational design pattern and it ensures that only one instance.
Code
class Singleton {
private static instance: Singleton;
private constructor() { }
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
We can get the same single instance using getInstance() anywhere in the same project code.
Test
class Singleton {
private static instance: Singleton;
private constructor() { }
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
}
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
Usage
We can add more business logic that we want to keep with a single instance.
class Singleton {
private static instance: Singleton;
private constructor(public counter: number) { }
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton(0);
}
return Singleton.instance;
}
public addCounter(): void {
++this.counter;
}
}
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
instance1.addCounter()
instance2.addCounter()
console.log(instance1.counter); // 2
console.log(instance2.counter); // 2
In this example, we add a variable for the counter and it is shared through the entire project.
'Web > JavaScript' 카테고리의 다른 글
[TypeScript] Mixins (0) | 2021.07.09 |
---|---|
[TypeScript] Generic (0) | 2021.07.05 |
[TypeScript] Class (0) | 2021.07.04 |
[TypeScript] Basic Types (0) | 2021.07.04 |
[Vue3] Getting Started with Vue3 + Electron (with Typescript, TailwindCSS) (0) | 2021.06.28 |
댓글