JavaScript之工厂模式
var Interface = function (name) {
if (arguments.length != 2) {
throw new Error("创建的接口不符合标准,必须有两个参数,第二个参数是接口的方法");
}
this.name = name;
this.methods = [];
var methods = arguments[1];
for (var i = 0; i < methods.length; i++) {
this.methods.push(methods[i]);
}
}
Interface.ensureImplements = function (obj) {
if (arguments.length < 2) {
throw new Error("要检查的接口必须传入接口对象的参数,所以参数的个数必须大于等于2")
}
for (var i = 1; i < arguments.length; i++) {
var intObj = arguments[i];
if (intObj.constructor != Interface) throw new Error(intObj + "接口的对象不正确");
var cmethods = intObj.methods;
for (var j = 0; j < cmethods.length; j++) {
if (!obj[cmethods[j]] || typeof obj[cmethods[j]] != "function") throw new Error("必须实现:" + cmethods[j] + "这个方法");
}
}
};
var ICar=new Interface("ICar",["assemble","wash","run"]);
var Car = function(){};
Car.prototype ={
assemble:function(){
alert("小车组装中");
},
wash:function(){
alert("小车清洗中");
},
run:function(){
alert("嘟嘟中");
}
}
var Truck = function(){};
Truck.prototype ={
assemble:function(){
alert("大卡车组装中");
},
wash:function(){
alert("大卡清洗中");
},
run:function(){
alert("轰隆隆");
}
}
var HongYong = {};
HongYong.CarFactory = {
createCar:function(model){
var car;
switch(model){
case "car":
car =new Car();
break;
case "truck":
car =new Truck();
break;
}
Interface.ensureImplements(car,ICar);
return car;
}
};
var CarShop = function(){};
CarShop.prototype = {
sellCar:function(model){
var car =HongYong.CarFactory.createCar(model);
car.assemble();
car.wash();
return car;
}
};
var c=new CarShop().sellCar("truck");
c.run();