Home Singleton Pattern in TypeScript
Post
Cancel

Singleton Pattern in TypeScript

Below is an awesome singleton pattern implementation I found deep in the bowels of StackOverflow using TypeScript (adapted from my favourite C# implementation).

This works well if you are wanting to create a single instance class for use through your application such as a logger or user service.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export class Logger {
  private static _instance:Logger = new Logger();

  constructor() {
    if(Logger._instance) {
      throw new Error("The Logger is a singleton class and cannot be created!");
    }

    Logger._instance = this;
  }

  public static getInstance() : Logger {
    return Logger._instance;
  }

  public trace(message: string) {
    console.log('[Trace] ' + message);
  }

  // ...
}

Using the Logger class is as simple as adding a line like this:

1
Logger.getInstance().trace("Hello world!")

… or more realistically:

1
this.logger = Logger.getInstance();

Happy coding :)

This post is licensed under CC BY 4.0 by the author.

Adding Castle Windsor to your WebAPI project

Pong (or my first attempt at JS game development)

Comments powered by Disqus.