一、享元模式是一种用于性能优化的模式,主要优化方式为,若系统中因为创建了大量类似的对象而导致内存占用过高,则可以考虑使用享元模式实现。
二、实例说明:
如果在浏览器中上传文件,若使用常规写法, 每上传一个文件,就会创建一个实例对象;如果上传2000个文件,那就有2000个对象,浏览器很可能出现假死状态。这种情况下,我们考虑适应享元模式。
三、实例:
var Upload = function( uploadType ){ this.uploadType = uploadType; }; Upload.prototype.delFile = function( id ){ uploadManager.setExternalState( id, this ); if( this.fileSize < 300 ){ return this.dom.parentNode.removeChild( this.dom ); } if( window.confirm('确定要删除该文件吗?' + this.fileName )){ return this.dom.parentNode.removeChild( this.dom); } }; var UploadFactory = (function(){ var createdFlyWeightObjs = {}; return { create: function( uploadType ){ if(createFlyWeightObjs[uploadType]){ return createdFlyWeightObjs[uploadType]; } return createdFlyWeightObjs[uploadType] = new Upload(uploadType); } } })(); var uploadManager = (function(){ var uploadDatabase = {}; return{ add: function(id, uploadType, fileName, fileSize){ var flyWeightObj = UploadFactory.create( uploadType ); var dom = document.createElement( 'div' ); dom.innerHTML = '<span>文件名称:'+fileName+',文件大小:' +fileSize + '</span>' + '<button>删除</button>'; dom.querySelector( ".delFile" ).onclick = function(){ flyWeightObj.delFile( id ); document.body.appendChild( dom ); uploadDatabase[ id ] = { fileName: fileName, fileSize: fileSize, dom: dom }; return flyWeightObj; }, setExternalState: functon( id, flyWeightObj ){ var uploadData = uploadDatabase[ id ]; for( var i in uploadData){ flyWeightObj[ i ] = uploadData[ i ]; } } } })();
然后需要写一个触发上传动作的startUpload函数:
var id = o; window.startUpload = function( uploadType, files ){ for( var i=0,file; file = fules[ i ++ ];){ var uploadObj = uploadManger.add( ++id, uploadType, file.fileName, file.fileSize ); } };
最后调用,如下:
startUpload( 'plugin', [ { fileName: '1.txt', fileSize: 1000 }, { fileName: '2.html', fileSize: 1000 }, { fileName: '3.txt', fileSize: 5000 } ]); startUpload( 'flash', [ { fileName: '4.txt', fileSize: 1000 }, { fileName: '5.html', fileSize: 1000 }, { fileName: '6.txt', fileSize: 5000 } ]);
四、解释:
调用时,有六个对象,但只有两个类型(plugin和flash),我们通过享元模式,在创建对象时,只有两个,如果上面提到的上传2000个文件,利用上面的代码,同样只创建两个对象,那么这就很好的解决了浏览器崩溃假死的问题。
更多关于JavaScript相关内容可查看本站专题:《javascript面向对象入门教程》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》