JS工厂模式

工厂模式定义:一个用于建立对象的接口,这个接口由子类决定实例化哪个类。该模式使一个类的实例化延迟到了子类。而子类能够重写接口方法以便建立的时候指定本身的对象类型。app

看不懂?不要紧,先看看下面的例子。dom

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);

再读读这句话:工厂模式定义一个用于建立对象的接口,这个接口由子类决定实例化哪个类。该模式使一个类的实例化延迟到了子类。而子类能够重写接口方法以便建立的时候指定本身的对象类型。this

这下是否是清楚多了,还不懂,不要紧,多敲几遍,多看几遍,就懂了。url

相关文章
相关标签/搜索