首页 > 语言 > JavaScript > 正文

JavaScript使用享元模式实现文件上传优化操作示例

2024-05-06 15:32:03
字体:
来源:转载
供稿:网友

本文实例讲述了JavaScript使用享元模式实现文件上传优化操作。分享给大家供大家参考,具体如下:

一、享元模式是一种用于性能优化的模式,主要优化方式为,若系统中因为创建了大量类似的对象而导致内存占用过高,则可以考虑使用享元模式实现。

二、实例说明:

如果在浏览器中上传文件,若使用常规写法, 每上传一个文件,就会创建一个实例对象;如果上传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 class="delFile">删除</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   }]);

四、解释:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选