4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptのSingletonパターン

Posted at

Singletonパターンとは

そのクラスのインスタンスが1つしか生成されないことを保証するデザインパターンのことである

Singletonパターン例

var singleton = function( name ){
  this.name = name;
};
Singleton.prototype.getName = function(){
alert ( this.name );
};
Singleton.getInstance = (function(){
  var instance = null;
  return function( name ){
    if ( !instance ){
      instance = new Singleton( name );
    }
  return instance;
}
})();

var a = Singleton.getInstance( 'instance1' );
var b = Singleton.getInstance( 'instance2' );

console.log(a === b); // true

上記の例、if ( !instance )文で何度getInstance()を呼び出しても常に同じインスタンスが返されることを保証できます。
が、上記の例では芳しくないところもあります:
上記の例でインスタンス取得方式はstatic的なgetInstance()が、new Class名()でインスタンスを取得するのが一般的です。

Singletonパターン例-その二

var Create = (function(){
  var instance;
  var Create = function( html ){
    if ( instance ){
      return instance;
    }
    this.html = html;
    return instance = this;
  };
  return Create;
})();
var a = new Create( 'instance1' );
var b = new Create( 'instance2' );
console.log(a === b); // true

上記の例も何度new CreateDiv()を呼び出しても常に同じインスタンスが返されることを保証できます。
が、この例も完璧とは言えないです。

  • 読みにくい
  • 同じインスタンスが返されることを保証できるロジックとクラス本体初期化処理が混ざる

Singletonパターン例-その三

var Create = function( html ){
  this.html = html;
  this.init(); // 初期化処理
};
CreateDiv.prototype.init = function(){
  // do something
};

// 同じインスタンスが返されることを保証するロジックを切り出す
var SingletonCreate = (function(){
  var instance;
  return function( html ){
    if ( !instance ){
      instance = new Create ( html );
    }
    return instance;
  }
})();
var a = new ProxySingletonCreateDiv( 'instance1' );
var b = new ProxySingletonCreateDiv( 'instance2' );
console.log(a === b); // true

やっといい感じになりました、
インスタンス返す処理とクラス本体処理を分けることで、

  • 読みやすい
  • 修正しやすい
  • Createみたいな他のクラスを追加される時に、SingletonCreateを流用できる

Singletonパターンのユースケース

I/O処理(ファイル出力のストリームを複数持つことはできません)などの単一インスタンスの数を制限したい場合

参考

  1. zeng tan.2015. Design Pattern And Development Practice Of JavaScript
4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?