/* 简单工厂 */
/* 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;
};
posted on 2009-11-04 16:40
becket_zheng 阅读(241)
评论(0) 编辑 收藏 所属分类:
网页web前端技术