JavaScript 工廠模式

2018-08-02 16:25 更新

工廠模式

工廠模式是另外一種關(guān)注對象創(chuàng)建概念的創(chuàng)建模式。它的領(lǐng)域中同其它模式的不同之處在于它并沒有明確要求我們使用一個構(gòu)造器。取而代之,一個工廠能提供一個創(chuàng)建對象的公共接口,我們可以在其中指定我們希望被創(chuàng)建的工廠對象的類型。

試想一下,在我們被要求創(chuàng)建一種類型的UI組件時,我們就有一個UI工廠。并不是通過直接使用new操作符或者通過另外一個構(gòu)造器來創(chuàng)建這個組件,我們?nèi)《南蛞粋€工廠對象索要一個新的組件。我們告知工廠我們需要什么類型的組件(例如:“按鈕”,“面板”),而它會將其初始化,然后返回供我們使用。

如果創(chuàng)建過程相當(dāng)復(fù)雜的話,那這會特別的有用,例如:如果它強(qiáng)烈依賴于動態(tài)因素或者應(yīng)用程序配置的話。

這個模式的一些例子可以在UI庫里面找到,例如ExtJS, 用于創(chuàng)建對象或者組件的方法可以被做更深層次的子類。 下面使用用我們之前的那些代碼來做的一個例子,通過使用構(gòu)造器模式邏輯來定義汽車。這個例子展示了Vehicle 工廠可以使用工廠模式來實現(xiàn)。

// Types.js - Constructors used behind the scenes

// A constructor for defining new cars
function Car( options ) {

  // some defaults
  this.doors = options.doors || 4;
  this.state = options.state || "brand new";
  this.color = options.color || "silver";

}

// A constructor for defining new trucks
function Truck( options){

  this.state = options.state || "used";
  this.wheelSize = options.wheelSize || "large";
  this.color = options.color || "blue";
}

// FactoryExample.js

// Define a skeleton vehicle factory
function VehicleFactory() {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {

  if( options.vehicleType === "car" ){
    this.vehicleClass = Car;
  }else{
    this.vehicleClass = Truck;
  }

  return new this.vehicleClass( options );

};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
            vehicleType: "car",
            color: "yellow",
            doors: 6 } );

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log( car instanceof Car );

// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );

方法1: 修改 VehicleFactory 實例使用 Truck 類

var movingTruck = carFactory.createVehicle( {
                      vehicleType: "truck",
                      state: "like new",
                      color: "red",
                      wheelSize: "small" } );

// Test to confirm our truck was created with the vehicleClass/prototype Truck

// Outputs: true
console.log( movingTruck instanceof Truck );

// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );

方法2: 做 VehicleFactory 的子類用于創(chuàng)建一個工廠類生產(chǎn) Trucks

function TruckFactory () {}
TruckFactory.prototype = new VehicleFactory();
TruckFactory.prototype.vehicleClass = Truck;

var truckFactory = new TruckFactory();
var myBigTruck = truckFactory.createVehicle( {
                    state: "omg..so bad.",
                    color: "pink",
                    wheelSize: "so big" } );

// Confirms that myBigTruck was created with the prototype Truck
// Outputs: true
console.log( myBigTruck instanceof Truck );

// Outputs: Truck object with the color "pink", wheelSize "so big"
// and state "omg. so bad"
console.log( myBigTruck );

何時使用工廠模式

當(dāng)被應(yīng)用到下面的場景中時,工廠模式特別有用:

  • 當(dāng)我們的對象或者組件設(shè)置涉及到高程度級別的復(fù)雜度時。
  • 當(dāng)我們需要根據(jù)我們所在的環(huán)境方便的生成不同對象的實體時。
  • 當(dāng)我們在許多共享同一個屬性的許多小型對象或組件上工作時。
  • 當(dāng)帶有其它僅僅需要滿足一種API約定(又名鴨式類型)的對象的組合對象工作時.這對于解耦來說是有用的。

何時不要去使用工廠模式

當(dāng)被應(yīng)用到錯誤的問題類型上時,這一模式會給應(yīng)用程序引入大量不必要的復(fù)雜性.除非為創(chuàng)建對象提供一個接口是我們編寫的庫或者框架的一個設(shè)計上目標(biāo),否則我會建議使用明確的構(gòu)造器,以避免不必要的開銷。

由于對象的創(chuàng)建過程被高效的抽象在一個接口后面的事實,這也會給依賴于這個過程可能會有多復(fù)雜的單元測試帶來問題。

抽象工廠

了解抽象工廠模式也是非常實用的,它的目標(biāo)是以一個通用的目標(biāo)將一組獨立的工廠進(jìn)行封裝.它將一堆對象的實現(xiàn)細(xì)節(jié)從它們的一般用例中分離。

抽象工廠應(yīng)該被用在一種必須從其創(chuàng)建或生成對象的方式處獨立,或者需要同多種類型的對象一起工作,這樣的系統(tǒng)中。

簡單且容易理解的例子就是一個發(fā)動機(jī)工廠,它定義了獲取或者注冊發(fā)動機(jī)類型的方式.抽象工廠會被命名為AbstractVehicleFactory.抽象工廠將允許像"car"或者"truck"的發(fā)動機(jī)類型的定義,并且構(gòu)造工廠將僅實現(xiàn)滿足發(fā)動機(jī)合同的類.(例如:Vehicle.prototype.driven和Vehicle.prototype.breakDown)。

var AbstractVehicleFactory = (function () {

    // Storage for our vehicle types
    var types = {};

    return {
        getVehicle: function ( type, customizations ) {
            var Vehicle = types[type];

            return (Vehicle ? new Vehicle(customizations) : null);
        },

        registerVehicle: function ( type, Vehicle ) {
            var proto = Vehicle.prototype;

            // only register classes that fulfill the vehicle contract
            if ( proto.drive && proto.breakDown ) {
                types[type] = Vehicle;
            }

            return AbstractVehicleFactory;
        }
    };
})();

// Usage:

AbstractVehicleFactory.registerVehicle( "car", Car );
AbstractVehicleFactory.registerVehicle( "truck", Truck );

// Instantiate a new car based on the abstract vehicle type
var car = AbstractVehicleFactory.getVehicle( "car" , {
            color: "lime green",
            state: "like new" } );

// Instantiate a new truck in a similar manner
var truck = AbstractVehicleFactory.getVehicle( "truck" , {
            wheelSize: "medium",
            color: "neon yellow" } );
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號