javascript抽象工厂写抽象对象写法

 

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值