JS設計模式--Factory(工廠)模式
摘要:
工廠模式
提供一個通用的介面來建立物件
示例
//Car建構函式
function Car(option) {
this.doors = option.doors || 4
this.color = option.color || 'red'
...
工廠模式
提供一個通用的介面來建立物件
示例
//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契約(亦稱鴨子型別)的其他物件的例項物件時。對解耦是很有用對。