undefined

技術的系メモブログ

Singleton Patternの簡易実装

var Hoge = function(){

  // よくみるSingletonの実装
  var self = arguments.callee;
  if(self.instance){
    return self.instance;
  }

  // getInstanceから呼ばれていなかったらthrowで投げる
  if(!self.isStatic){
    throw Error(/* Error */);
  }

  // ここで呼ばれたことをリセット
  delete self.isStatic;
  return this;
};

Hoge.getInstance = function(){

  // getInstanceから呼ばれたっていう情報
  Hoge.isStatic = true;

  // constructor実行
  return Hoge.apply(Hoge.prototype, arguments);
};


var hoge = new Hoge(); // throw Error
var hoge = Hoge.getInstance();


っていうのをふと今思いついたんですが、どうなんですかね。