ES6 Singleton vs实例化一次类 [英] ES6 Singleton vs Instantiating a Class once

查看:102
本文介绍了ES6 Singleton vs实例化一次类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到使用ES6类使用单例模式的模式,我想知道为什么我会使用它们而不是仅仅实例化文件底部的类并导出实例。这样做有什么负面的缺点吗?例如:

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导出实例:

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;

用法:

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

使用以下Singleton模式有什么区别?是否有任何理由使用另一个?我真的更好奇,知道我给出的第一个例子是否有我不知道的问题。

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模式:

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 difference is if you want to test things.

假设你有 api.spec.js 测试文件。并且你的API thingy有一个依赖项,比如那些常量。

Say you have api.spec.js test file. And that your API thingy has one dependency, like those Constants.

具体来说,两个版本中的构造函数都有一个参数,你的常量 import。

Specifically, constructor in both your versions takes one parameter, your Constants import.

所以你的构造函数如下所示:

So your constructor looks like this:

class API {
    constructor(constants) {
      this.API_URL = constants.API_URL;
    }
    ...
}



// single-instance method first
import API from './api';
describe('Single Instance', () => {
    it('should take Constants as parameter', () => {
        const mockConstants = {
            API_URL: "fake_url"
        }
        const api = new API(mockConstants); // all good, you provided mock here.
    });
});

现在,通过导出实例,没有嘲弄。

Now, with exporting instance, there's no mocking.

import API from './api';
describe('Singleton', () => {
    it('should let us mock the constants somehow', () => {
        const mockConstants = {
            API_URL: "fake_url"
        }
        // erm... now what?
    });
});

通过导出实例化对象,您无法(轻松且理智地)更改其行为。

With instantiated object exported, you can't (easily and sanely) change its behavior.

这篇关于ES6 Singleton vs实例化一次类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆