这次给大家带来js设计模式之工厂模式详解,使用js工厂模式的注意事项有哪些,下面就是实战案例,一起来看一下。
概念:工厂模式定义了一个用于创建对象的接口,这个接口由子类决定实例化哪一个类,该模式是一个类的实例化延迟到了子类。而子类可以重写接口的方法以便创建的时候指定自己的对象类型(抽象工厂)
作用和注意事项
作用:对象构建十分复杂。
需要依赖具体的环境创建不同的实例
处理大量的具有相同属性的小对象
注意事项:不能滥用工厂,有时候仅仅是给代码增加复杂度
使用方法
我们通过一个例子来演示这个问题,就像我们这个工厂里要生产不同类型的产品一样,我们每个类型写在一个方法,这样我们在生产的时候直接调用这个办法就行了。 那请看这段代码:
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);相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上就是JS设计模式之工厂模式详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号