Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Singleton vs Instantiating a Class once

I see patterns which make use of a singleton pattern using ES6 classes and I am wondering why I would use them as opposed to just instantiating the class at the bottom of the file and exporting the instance. Is there some kind of negative drawback to doing this? For example:

ES6 Exporting Instance:

import Constants from '../constants';  class _API {   constructor() {     this.url = Constants.API_URL;   }    getCities() {     return fetch(this.url, { method: 'get' })       .then(response => response.json());   } }  const API = new _API(); export default API; 

Usage:

import API from './services/api-service' 

What is the difference from using the following Singleton pattern? Are there any reasons for using one from the other? Im actually more curious to know if the first example I gave can have issues that I am not aware of.

Singleton Pattern:

import Constants from '../constants';  let instance = null;  class API {   constructor() {      if(!instance){       instance = this;     }      this.url = Constants.API_URL;      return instance;   }    getCities() {     return fetch(this.url, { method: 'get' })       .then(response => response.json());   } }  export default API; 

Usage:

import API from './services/api-service';  let api = new API() 
like image 847
Aaron Avatar asked Jan 21 '18 12:01

Aaron


People also ask

Are ES6 modules singleton?

The ES6 Way — modulesES6 Modules are singletons. Thus all you have to do is define your object in a module.

What is the best way to subclass singletons?

I would argue the most common way to implement a singleton is to use an enum with one instance. That might be a "better" way but definitely not the most common way. In all the projects I have worked on, Singletons are implemented as I have shown above.

Is multiple instantiation possible with singleton class?

Ans: NO. This is the simple example for Singleton class in java.


1 Answers

I would recommend neither. This is totally overcomplicated. If you only need one object, do not use the class syntax! Just go for

import Constants from '../constants';  export default {   url: Constants.API_URL,   getCities() {     return fetch(this.url, { method: 'get' }).then(response => response.json());   } }; 

import API from './services/api-service' 

or even simpler

import Constants from '../constants';  export const url = Constants.API_URL; export function getCities() {   return fetch(url, { method: 'get' }).then(response => response.json()); } 

import * as API from './services/api-service' 
like image 181
Bergi Avatar answered Sep 23 '22 12:09

Bergi