LoginSignup
49
39

More than 5 years have passed since last update.

ES2015 の Class で Singleton

Posted at

状態を持つインスタンスを、異なるファイルやクラスで使いまわすケースです。例としてキーと値を保持するコンテナ的なものをシングルトンで運用する場合は、次のように new でインスタンス化したものを export するだけです。

container.es6
class Container {
  constructor() {
    this.map = new Map;
  }

  set(key, value) {
    this.map.set(key, value);
  }

  get(key) {
    return this.map.get(key);
  }
}

export default new Container();

あるファイルでコンテナに値をセットすれば、

some.es6
import container from './container.es6';

// ...

// コンテナにキーと値をセット
container.set('key1', 'value1');

// ...

別のファイルでもコンテナから値を取り出せます。

app.es6
import container from './container.es6';

// ...

console.log(container.get('key1')); // value1 が出力される

// ...

一度 import したものは再利用される為です。

49
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
39