工厂模式提供一个通用的接口来创建对象示例 //Car构造函数 function Car(option) { this.doors = option.doors || 4 this.color = option.color || ‘red’ this.state = option.state || ‘brand new’ } //Truck构造函数 function Truck(option) { this.color = option.color || ‘blue’ this.wheelSize = option.wheelSize || ’large’ this.state = option.state || ‘used’ } //Vehicle工厂 function VehicleFactory() {} VehicleFactory.prototype.vehicleClass = Car VehicleFactory.prototype.createVehicle = function(option) { if(option.vehicleType == ‘car’) { this.vehicleClass = Car }else { this.vehicleClass = Truck } return new this.vehicleClass(option) } //创建生成汽车的工厂实例 var carFactory = new VehicleFactory() var car = carFactory.createVehicle({ vehicleType: ‘car’, color: ‘yellow’, doors: 6 }) console.log(car instanceof Car) console.log(car) //true //Car {doors: 6, color: “yellow”, state: “brand new”} var movingTruck = carFactory.createVehicle({ vehicleType: ’truck’, color: ‘red’, state: ’like new’, wheelSize: ‘small’ }) console.log(movingTruck instanceof Truck) console.log(movingTruck) //true //Truck {color: “red”, state: “like new”, wheelSize: “small”}适用场景当对象或组建设置涉及高复杂性时当需要根据所在当不同环境轻松生成对象当不同实例时当处理很多共享相同属性当小型对象或组件时在编写只需要满足一个API契约(亦称鸭子类型)的其他对象的实例对象时。对解耦是很有用对。JS设计模式系列文章JS设计模式之Factory(工厂)模式JS设计模式之Singleton(单例)模式JS设计模式之Facade(外观)模式JS设计模式之Module(模块)模式、Revealing Module(揭示模块)模式