- 指向性メモ::2005-02-24::JavaScriptでデザインパターンその2
- prototype.js でデザインパターン - Singleton
- JavaScriptのデザインパターン - Singleton
石川さんの記事のコメントに解決法があるが、別の解決法を考えてみた。そもそも new が出来ないクラスを作る、というもの。石川さんの記事と同じ例で記述するとこんな感じ。
var Earth = {
instance : null,
getInstance : function(){
if(this.instance === null){
function Temp(){};
Temp.prototype = {
population : 2,
increasePopulation : function(){
this.population *= 2;
},
getPopulation : function(){
return this.population;
}
}
this.instance = new Temp;
}
return this.instance;
}
}
//new Earth //この行を実行するとエラー
//使い方
var e1 = Earth.getInstance();
var e2 = Earth.getInstance();//e1 == e2
e1.getPopulation();//2
e2.increasePopulation();
e2.getPopulation();//4
e1.getPopulation();//4
- 問題点
- 標準的な方法でつくったクラスやオブジェクトと若干挙動が異なる。(
e1.constructor != Earth , e1.[[Prototype]] != Earth.prototype) new Earthは出来ないが、Earth.getInstance.apply({instance : null})は出来る。
難しく考えすぎていた。prototype.js を使うという前提で、
var Singleton = Class.create();
(function(){
Singleton.prototype.initialize = function(){};
var singleton = new Singleton;
Singleton.prototype.initialize = null;
Singleton.getInstance = function(){
return singleton;
};
})();
var a = Singleton.getInstance();
var b = Singleton.getInstance();
//print()は適当に定義
print(a == b);//true
//var c = new Singleton;
//上の行を実行するとエラー
上記のようにすればよい。