深入理解JavaScript系列(28):設計模式之原廠模式

來源:互聯網
上載者:User
介紹

與建立型模式類似,原廠模式建立對象(視為工廠裡的產品)時無需指定建立對象的具體類。

原廠模式定義一個用於建立對象的介面,這個介面由子類決定執行個體化哪一個類。該模式使一個類的執行個體化延遲到了子類。而子類可以重寫介面方法以便建立的時候指定自己的物件類型。

這個模式十分有用,尤其是建立對象的流程賦值的時候,比如依賴於很多設定檔案等。並且,你會經常在程式裡看到Factory 方法,用於讓子類類定義需要建立的物件類型。

本文

下面這個例子中,是應用了Factory 方法對第26章建構函式模式代碼的改進版本:

var Car = (function () {
var Car = function (model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
};
return function (model, year, miles) {
return new Car(model, year, miles);
};
})();

var tom = new Car("Tom", 2009, 20000);
var dudu = new Car("Dudu", 2010, 5000);

不好理解的話,我們再給一個例子:

var productManager = {};

productManager.createProductA = function () {
console.log('ProductA');
}

productManager.createProductB = function () {
console.log('ProductB');
}

productManager.factory = function (typeType) {
return new productManager[typeType];
}

productManager.factory("createProductA");

如果還不理解的話,那我們就再詳細一點咯,假如我們想在網頁面裡插入一些元素,而這些元素類型不固定,可能是圖片,也有可能是串連,甚至可能是文本,根據原廠模式的定義,我們需要定義工廠類和相應的子類,我們先來定義子類的具體實現(也就是子函數):

var page = page || {};
page.dom = page.dom || {};
//子函數1:處理文本
page.dom.Text = function () {
this.insert = function (where) {
var txt = document.createTextNode(this.url);
where.appendChild(txt);
};
};

//子函數2:處理連結
page.dom.Link = function () {
this.insert = function (where) {
var link = document.createElement('a');
link.href = this.url;
link.appendChild(document.createTextNode(this.url));
where.appendChild(link);
};
};

//子函數3:處理圖片
page.dom.Image = function () {
this.insert = function (where) {
var im = document.createElement('img');
im.src = this.url;
where.appendChild(im);
};
};

那麼我們如何定義工廠處理函數呢?其實很簡單:

page.dom.factory = function (type) {
return new page.dom[type];
}

使用方式如下:

var o = page.dom.factory('Link');
o.url = 'http://www.cnblogs.com';
o.insert(document.body);

至此,原廠模式的介紹相信大家都已經瞭然於心了,我就不再多敘述了。

總結

什麼時候使用原廠模式

以下幾種情景下原廠模式特別有用:

  1. 對象的構建十分複雜
  2. 需要依賴具體環境建立不同執行個體
  3. 處理大量具有相同屬性的小對象

什麼時候不該用原廠模式

不濫用運用原廠模式,有時候僅僅只是給代碼增加了不必要的複雜度,同時使得測試難以運行下去。

轉自:湯姆大叔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.