js设计模式8 Factory Pattern

在Factory类里可以预先装好类的定义 要的时候去取出来
        function Car(options){
  		this.color = options.color || "red";
  		this.name = options.name || "bmw";
  		this.doors = options.door || 4;
  		}
  		
  	function Truck(options){
  		this.size = options.size || "large";
  		this.wheelSize = options.wheelSize || "huge";
  		this.name = options.name || "truck";
  		}
  		
  	function Factory(){}
  	Factory.prototype.vehicleType = Car;
  	Factory.prototype.createVehicle = function(options){
  		if(options.vehicleType=="car"){
  			this.vehicleType = Car;
  			}else{
  				this.vehicleType = Truck;
  				}
  		return new this.vehicleType(options);
  		}
  		
  	//test
  	var factory = new Factory();
  	var truck = factory.createVehicle({"vehicleType":"truckkk","wheelSize":"small"});
  	alert(truck.size+"-----"+truck.wheelSize+"--------"+truck.name);
  	//继承该工厂 可以稍作修改
  	function TruckFactory(){}
  	TruckFactory.prototype = Factory;
  	TruckFactory.prototype.vehicleType = Truck;

也可以把工厂类升级一下 变成可以装配的工厂

var abstractFactory = (function(){
  		var types = {};
  		return {
  			getVehicle:function(type,options){
  				var vehicleType = types[type];
  				return (vehicleType)?(new vehicleType(options)):null;
  				},
  			registerVehicleType:function(type,Vehicle){
  				//可以做一些检查是否 实现了必要的方法
  				//if(Vehicle.prototype.xxx){
  					types[type] = Vehicle;
  					//}
  				}
  			}
  		})();
  	abstractFactory.registerVehicleType("car",Car);
  	abstractFactory.registerVehicleType("truck",Truck);
  	var truck = abstractFactory.getVehicle("truck",{"vehicleType":"truckkk","wheelSize":"small"});
  	alert(truck.size+"-----"+truck.wheelSize+"--------"+truck.name);
这样更灵活一点

你可能感兴趣的:(js设计模式8 Factory Pattern)