[JS] Singleton

Suyeon·2020년 12월 15일
0

Javascript

목록 보기
25/31
post-thumbnail

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.

ES6 Module instance

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();

Singleton Class

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;
profile
Hello World.

0개의 댓글