Skip to content

Commit

Permalink
Merge pull request torokmark#13 from rugpanov/master
Browse files Browse the repository at this point in the history
Improve SingletonPattern example
  • Loading branch information
torokmark authored Jun 19, 2018
2 parents 00fff1c + ed2dde2 commit c8d3500
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
4 changes: 2 additions & 2 deletions singleton/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ namespace SingletonPattern {
export namespace Demo {

export function show() : void {
var singleton1 = SingletonPattern.Singleton.Instance();
var singleton2 = SingletonPattern.Singleton.Instance();
const singleton1 = SingletonPattern.Singleton.getInstance();
const singleton2 = SingletonPattern.Singleton.getInstance();

if (singleton1 === singleton2) {
console.log("two singletons are equivalent");
Expand Down
14 changes: 8 additions & 6 deletions singleton/singleton.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
namespace SingletonPattern {
export class Singleton {
// A variable which stores the singleton object. Intially,
// A variable which stores the singleton object. Initially,
// the variable acts like a placeholder
private static singleton: Singleton = null;
private static singleton: Singleton;

// private constructor so that no instance is created
private constructor() {
}

// This is how we create a singleton object
public static Instance(): Singleton {
public static getInstance(): Singleton {
// check if an instance of the class is already created
if (this.singleton == null) {
if (!Singleton.singleton) {
// If not created create an instance of the class
// store the instance in the variable
this.singleton = new Singleton();
Singleton.singleton = new Singleton();
}
// return the singleton object
return this.singleton
return Singleton.singleton;
}
}
}

0 comments on commit c8d3500

Please sign in to comment.