JS工廠模式

weixin_33843409發表於2015-11-23

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

看不懂?沒關係,先看看下面的例子。

var produceManager = {};
produceManager.createProduceA = function(){
    console.log("ProduceA");
}
produceManager.createProduceB = function(){
    console.log("ProduceB");
}
produceManager.factory = function(type){
    return new produceManager[type];
}
var produce = produceManager.factory("createProduceA");

如果不好理解,我們舉個實際一點的例子。假設我們要在一個頁面上插入一些元素,但這些元素不確定,可能是圖片,可能是連結,可能是文字。我們需要定義工廠類與子類(產品類)。

var page = page || {};
page.dom = page.dom || {};
//子函式:處理文字
page.dom.Text = function(){
    this.insert = function(where){
        var txt = document.createTextNode(this.url);
        where.appendChild(txt);
    };
};
//子函式:處理連結
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);
    };
};
//子函式:處理圖片
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];
};

//test:
var o = page.dom.factory("Link");
o.url = "http://abc.com";
o.insert(document.body);

再讀讀這句話:工廠模式定義一個用於建立物件的介面,這個介面由子類決定例項化哪一個類。該模式使一個類的例項化延遲到了子類。而子類可以重寫介面方法以便建立的時候指定自己的物件型別。

這下是不是清楚多了,還不懂,沒關係,多敲幾遍,多看幾遍,就懂了。

相關文章