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()
Another reason to use Singleton Pattern is in some frameworks (like
Polymer 1.0
) you can't useexport
syntax.That's why second option (Singleton pattern) is more useful, for me.
Hope it helps.
I would recommend neither. This is totally overcomplicated. If you only need one object, do not use the
class
syntax! Just go foror even simpler
In addition to all the answers given, a
class
has the property of getting extended (inheritance). How possibly do you think you can let developers extend yourclass
, if all you are exporting is a single instance from its module file?Both are different ways. Exporting a class like as below
and then importing like as below in multiple files would point to same instance and a way of creating Singleton pattern.
Whereas the other way of exporting the class directly is not singleton as in the file where we are importing we need to new up the class and this will create a separate instance for each newing up Exporting class only:
Importing class and newing up
The difference is if you want to test things.
Say you have
api.spec.js
test file. And that your API thingy has one dependency, like those Constants.Specifically, constructor in both your versions takes one parameter, your
Constants
import.So your constructor looks like this:
Now, with exporting instance, there's no mocking.
With instantiated object exported, you can't (easily and sanely) change its behavior.