js_desain_factory
Factory
ファクトリの目的はその名の通り、オブジェクトを生成します。
共通の親オブジェクトを継承し個別の機能を専門の静的メソッドに実装します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| var CarMaker = function() { };
CarMaker.prototype.drive = function() {
this.gas = this.gas - 20;
if(this.gas > 0) { console.log('ぶーん ' + this.speed +'km で走るよ'); console.log('残りのガソリンは ' + this.gas +'L だよ'); } else { console.log('ガス欠だよ'); }
};
## static Method CarMaker.factory = function(type) {
var constr = type; var newcar;
if(typeof CarMaker[constr] !== 'function') { throw { name: 'Error', message: constr + 'は存在しません' }; }
CarMaker[constr].prototype = new CarMaker();
// 新しいインスタンスの作成 newcar = new CarMaker[constr](); return newcar;
};
CarMaker.FORMURA1 = function() {
this.speed = 350; this.gas = 150;
};
var F1Car = CarMaker.factory('FORMURA1'); F1Car.drive();
|
Object.prototype
Comments