ES2015でSingleton
イマイチ感がすごすぎる…。
class Singleton { constructor() {} echo() { console.log('hello') } static getInstance() { if (Singleton.instance === null) { Singleton.instance = new Singleton() } return Singleton.instance } } Singleton.instance = null const instance1 = Singleton.getInstance() const instance2 = Singleton.getInstance() console.log(instance1 === instance2) instance1.echo()
getInstance()経由で唯一のインスタンスもらえるのはまあいいのですが、
外からnew出来ちゃうのが問題ですねこれ。
どうSingletonを実現するのがスマートなんだろうか。