Last time we discussed theĀ importance of Singleton design pattern and how to implement same in CoffeeScript. Es6 classes are little bit different from Coffeescript as you cannot define properties directly inside class defination.

Which means following is not possible in Es6 classes.

class Cache{  
   let instance = null;
}

In order to avoid re-instantiation of same class , we need to maintain it’s state inside a variable which itself is not dependent upon the same class.

Singleton class in es6

Following is my approach to have a single instance of a class , no matter how many time you reinitiate it.

/* 
  * Setting up block level variable to store class state
  * , set's to null by default.
*/
let instance = null;

class Cache{  
    constructor() {
        if(!instance){
              instance = this;
        }

        // to test whether we have singleton or not
        this.time = new Date()

        return instance;
      }
}

Testing singleton

On above class we have defined a time property to make sure we have singleton working properly.

 let cache = new Cache()
 console.log(cache.time);

 setTimeout(function(){
   let cache = new Cache();
   console.log(cache.time);
 },4000);

If it prints the same time for both the instances, it means we have a working singleton.