提供一個通用的接口來建立對象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(揭示模塊)模式函數