提供一个通用的接口来建立对象segmentfault
示例设计模式
//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"}
JS设计模式之Obeserver(观察者)模式、Publish/Subscribe(发布/订阅)模式
JS设计模式之Factory(工厂)模式
JS设计模式之Singleton(单例)模式
JS设计模式之Facade(外观)模式
JS设计模式之Module(模块)模式、Revealing Module(揭示模块)模式函数