JS 設計模式 六(工廠模式)

工廠模式

以前講了接口,封裝,繼承,單例等,如今就須要應用這些特性來完成一些設計模式了。首先吧以前的代碼打包成一個新的JSjavascript

DesignPattern.js

// 設計模式公用代碼     
exports.Interface = function (object, methods) {
  for (var i = 0, len = methods.length; i < len; i++) {
    if (typeof methods[i] !== 'string') {
      throw new Error('Interface constructor expects method names to be passed in as a string.');
    }
    object[methods[i]] = function () {
      throw new Error(this.constructor.name + ' Interface function is undefined');
    };
  }
};

exports.Extend = function (subClass, superClass) {
  var F = function () {
  };
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;

  subClass.superclass = superClass.prototype;
  if (superClass.prototype.constructor == Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  }
}

exports.Clone = function (object) {
  function F() {
  }

  F.prototype = object;
  return new F;
}

exports.Augment = function (receivingClass, givingClass) {
  if (arguments[2]) { // Only give certain methods.
    for (var i = 2, len = arguments.length; i < len; i++) {
      receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
    }
  }
  else { // Give all methods.
    for (methodName in givingClass.prototype) {
      if (!receivingClass.prototype[methodName]) {
        receivingClass.prototype[methodName] = givingClass.prototype[methodName];
      }
    }
  }
}

工廠模式要點

1.工廠接口是工廠方法模式的核心,與調用者直接交互用來提供產品。java

2.工廠實現決定如何實例化產品,是實現擴展的途徑,須要有多少種產品,就須要有多少個具體的工廠實現。設計模式

適用場景:

1.在任何須要生成複雜對象的地方,均可以使用工廠方法模式。有一點須要注意的地方就是複雜對象適合使用工廠模式,而簡單對象,無需使用工廠模式。測試

2.工廠模式是一種典型的解耦模式,迪米特法則在工廠模式中表現的尤其明顯。假如調用者本身組裝產品須要增長依賴關係時,能夠考慮使用工廠模式。將會大大下降對象之間的耦合度。ui

3.當須要系統有比較好的擴展性時,能夠考慮工廠模式,不一樣的產品用不一樣的實現工廠來組裝。this

代碼

var DP = require("./DesignPattern.js");

function CarFactory() {//定義工廠
  this.run = function () {
    console.log(this.productCar()+'啓動');
  }
  DP.Interface(this, ['productCar']);
}

function PorscheFactory() {//實例化保時捷工廠
  this.__proto__ = new CarFactory();
  this.productCar = function () {
    return '保時捷';
  }
}

function TractorFactory() {//實例化拖拉機工廠並不重寫接口測試接口定義
  this.__proto__ = new CarFactory();
}

var Porsche = new PorscheFactory();
Porsche.run();


var Tractor = new TractorFactory();
Tractor.run();

總結

因爲javascript沒有原生接口,因此須要本身想方法來實現接口這個原則。使用了接口之後就能夠方便實現工廠模式。prototype

相關文章
相關標籤/搜索