<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="container"></div>
<script language="javascript">
var VehicleFactory=function(subType,superType){
//判断抽象工厂中是否有抽象类
if(typeof VehicleFactory[superType]==='function'){
function F(){};
F.prototype=new VehicleFactory[superType]();
subType.constructor=subType;
subType.prototype=new F();
}else{
throw new Error('未创建该抽象类');
}
};
//这里开始是小汽车的抽象类
VehicleFactory.Car=function(){
this.type='car';
};
VehicleFactory.Car.prototype={
getPrice:function(){
return new Error('抽象方法不能调用');
},
getSpeed:function(){
return new Error('抽象方法不能调用');
}
};
//这里是公交车的抽象类
VehicleFactory.Bus=function(){
this.type='bus';
};
VehicleFactory.Bus.prototype={
getPrice:function(){
return new Error('抽象方法不能调用');
},
getSpeed:function(){
return new Error('抽象方法不能调用');
}
};
//这里是大卡车的抽象类
VehicleFactory.Truck=function(){
this.type='truck';
};
VehicleFactory.Truck.prototype={
getPrice:function(){
return new Error('抽象方法不能调用');
},
getSpeed:function(){
return new Error('抽象方法不能调用');
}
};
//建立子类
var BMW=function(price,speed){
this.price=price;
this.speed=speed;
};
//抽象工厂实际对car抽象类的继承
VehicleFactory(BMW,'Car');
//子类BMW的原型方法
BMW.prototype.getPrice=function(){
return this.price;
};
BMW.prototype.getSpeed=function(){
return this.speed;
};
var shudu=function(price,speed){
this.price=price;
this.speed=speed;
};
//抽象工厂实现对Bus抽象类的继承
VehicleFactory(shudu,'Bus');
shudu.prototype.getPrice=function(){
return this.price;
};
shudu.prototype.getSpeed=function(){
return this.speed;
};
shudu.prototype.getType=function(){
return this.type;
};
var s=new shudu(1000000,150);
console.log(s.getPrice()); //输出价格1000000
console.log(s.type); //输出抽象类中的种类 bus(抽象类中的this.type=bus)
</script>
</body>
</html>