/* 简单工厂 */
/* BicycleShop class */
var BicycleShop = function() {};
BicycleShop.prototype = {
sellBicycle: function(model) {
var bicycle;
switch(model) {
case 'The SpeedSter':
bicycle = new SpeedSter();
break;
case 'The Lowrider':
bicycle = new Lowrider();
break;
case 'The Comfort Cruiser':
default:
bicycle = new ComfortCruiser();
}
Interface.ensureImplements(bicycle, Bicycle);
bicycle.assemble();
bicycle.wash();
return bicycle;
}
};
/* The Bicycle interface. */
var Bicycle = new Interface('Bicycle', ['assemble','wash','ride','repaid']);
/* Speedster class. */
var Speedster = function() {//implements Bicycle
//...
};
Speedster.prototype = {
accemble: function() {
},
wash: function() {
},
ride: function() {
},
repaid: function() {
}
};
var californiaCruisers = new BicycleShop();
var yourNewBike = californiaCruisers.sellBicyCle('The Speedster');
/* BicycleFactory namespace. */
var BicycleFactory ={
createBicycle: function(model) {
var bicycle;
switch(model) {
case 'The SpeedSter':
bicycle = new SpeedSter();
break;
case 'The Lowrider':
bicycle = new Lowrider();
break;
case 'The Comfort Cruiser':
default:
bicycle = new ComfortCruiser();
}
Interface.ensureImplements(bicycle, Bicycle);
return bicycle;
}
};
/* BicycleShop class, improved */
var BicycleShop = function() {};
BicycleShop.prototype = {
var bicycle = BicycleFactory.createBicycle(model);
bicycle.assemble();
bicycle.wash();
return bicycle;
};
/* 真正的工厂模式 */
/* BicycleShop class(abstract). */
var BicycleShop = function() {};
BicycleShop.prototype = {
sellBicycle: function(model) {
var bicycle = this.createBicycle(model);
bicycle.assemble();
bicycle.wash();
return bicycle;
},
createBicycle: function(model) {
throw new Error('Unsupported operation on an abstract class.');
}
};
/* AcmeBicycleShop class. */
var AcmeBicycleShop = function() {};
extend(AcmeBicycleShop, BicycleShop);//类式继承
AcmeBicycleShop.prototype.createBicycle = function(model) {
var bicycle;
switch(model) {
case 'The SpeedSter':
bicycle = new SpeedSter();
break;
case 'The Lowrider':
bicycle = new Lowrider();
break;
case 'The Comfort Cruiser':
default:
bicycle = new ComfortCruiser();
}
}
Interface.ensureImplements(bicycle, Bicycle);
return bicycle;
};
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛