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()
The ES6 Way — modulesES6 Modules are singletons. Thus all you have to do is define your object in a module.
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.
Ans: NO. This is the simple example for Singleton class in java.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With