Singleton is a design pattern that restricts the instantiation of a class to one object. A singleton should be immutable by the consuming code. Usually, the goal is to manage global application state.
- It provides a global point of access to it.
- Source of config settings for a web app (initiated with an API key)
- It saves memory because only single obect is reused not created at each request.
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;
// index.js
import _API from './_API';
const instance1 = new _API();
class _API {
constructor() {
this.url = Constants.API_URL;
}
getCities() {
return fetch(this.url, { method: 'get' })
.then(response => response.json());
}
}
const API = new _API();
Object.freeze(API)
export default API;