JavaScript设计模式-工厂模式

工厂模式建立对象(视为工厂里的产品)时无需指定建立对象的具体类。
工厂模式定义一个用于建立对象的接口,这个接口由子类决定实例化哪个类。该模式使一个类的实例化延迟到了子类。而子类能够重写接口方法以便建立的时候指定本身的对象类型。
这个模式十分有用,尤为是建立对象的流程赋值的时候,好比依赖于不少设置文件等。而且,你会常常在程序里看到工厂方法,用于让子类定义须要建立的对象类型。
// 安全模式建立的工厂类
var Factory = function (type, content) {
    if (this instanceof Factory) {
        return this[type](content);
    } else {
        return new Factory(type, content);
    }
}

// 工厂原型中设置建立全部类型数据的基类
Factory.prototype = {
    Yuwen: function (content) {
        console.log(content);
    },
    Shuxue: function(content) {
        console.log(content);
    },
    English: function(content) {
        console.log(content);
    }
}

var data = [
    {
        type: 'Yuwen',
        content: '我是语文老师!'
    },
    {
        type: 'Shuxue',
        content: '我是数学老师!'
    },
    {
        type: 'English',
        content: '我是英语老师!'
    }
];

for (var i = 0; i < data.length; i++) {
    Factory(data[i].type, data[i].content);
}

源码中的工厂模式javascript

  • Vue中的工厂模式

和原生的document.createElement 相似,Vue在生成虚拟DOM的时候,提供了createElement方法用来生成VNode,用来做为真实DOM节点的映射:java

createElement('div', { class: 'body' }, [
    createElement('a', { class: 'title', attrs: { href: 'www.baidu.com' } }),
    createElement('span', { class: 'content' }, '百度网址')
])

createElement 函数结构大概以下:node

class Vnode (tag, data, children) { ... }

function createElement(tag, data, children) {
      return new Vnode(tag, data, children)
}

能够看到Vue提供的 createElement 工厂方法封装了复杂的建立过程,对于使用者来讲就很方便了。安全

何时使用工厂模式函数

如下几种情景下工厂模式特别有用:测试

  • 对象的构建十分复杂
  • 须要依赖具体环境建立不一样实例
  • 处理大量具备相同属性的小对象

何时不应用工厂模式this

不滥用运用工厂模式,有时候仅仅只是给代码增长了没必要要的复杂度,同时使得测试难以运行下去。spa

相关文章
相关标签/搜索