Skip to content

Commit 0e2785e

Browse files
authored
new approach for singleton
1 parent f0a4cf2 commit 0e2785e

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

singleton/src/singleton.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,24 @@
1-
namespace SingletonPattern {
2-
export class Singleton {
3-
private static instance: Singleton;
4-
5-
constructor() {}
6-
7-
static get Instance() {
8-
if (this.instance === null || this.instance === undefined) {
9-
this.instance = new Singleton();
1+
namespace Singleton {
2+
class Singleton {
3+
// A variable which stores the singleton object. Intially,
4+
// the variable acts like a placeholder
5+
private static __singleton: Singleton = null;
6+
// private constructor so that no instance is created
7+
private constructor() {
8+
}
9+
// This is how we create a singleton object
10+
public static getInstance(): Singleton {
11+
// check if an instance of the class is already created
12+
if (this.__singleton == null) {
13+
// If not created create an instance of the class
14+
// store the instance in the variable
15+
this.__singleton = new Singleton();
1016
}
11-
return this.instance;
17+
// return the singleton object
18+
return this.__singleton
19+
}
20+
public getSingletonName(name: string) {
21+
alert(`Singleton is ${name}`)
1222
}
1323
}
1424
}

0 commit comments

Comments
 (0)