LoginSignup
0
0

More than 5 years have passed since last update.

6日目 => デザインパターン(シングルトンパターン)

Posted at

はじめに

次はシングルトン。

説明

シングルトンパターン

作成されるクラスのインスタンスが1つのオブジェクトに制限。
JavaScriptのシングルトンは関数へのアクセスポイントをただ1つ提供。

var singleton = (function(){
  // シングルトンへの参照保持
  var instance;

  function init(){
    // プライベートメソッド
    function introduction(){
      console.log("I am John.");
    }

    // プライベート変数
    var age = 28;

    return {
      // パブリックメソッド
      publicIntroduction: function(){
        console.log("John is " + age + "years old.");
      },

      // パブリック変数
      publicAge: 18
    }
  };

  return {
    // インスタンスが存在するかのチェックと
    // 存在しなかった場合の作成処理
    getInstance: function(){
      if(!instance){
        instance = init();
      }

      return instance;
    }
  }
}());


var singletonA = singleton.getInstance();
var singletonB = singleton.getInstance();

console.log(singletonA === singletonB ? "2つは同じインスタンス" : "別物");
// 2つは同じインスタンス

参考

  • JavaScriptデザインパターン
0
0
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
0
0