用享元模式寫一個(gè)文件上傳控件

享元(flyweight)模式是一種用于性能優(yōu)化的模式,“fly”在這里是蒼蠅的意思,意為蠅量級(jí)。享元模式的核心是運(yùn)用共享技術(shù)來有效支持大量細(xì)粒度的對(duì)象。

如果系統(tǒng)中因?yàn)閯?chuàng)建了大量類似的對(duì)象而導(dǎo)致內(nèi)存占用過高,享元模式就非常有用了。在JavaScript中,瀏覽器特別是移動(dòng)端的瀏覽器分配的內(nèi)存并不算多,如何節(jié)省內(nèi)存就成了一件非常有意義的事情。

網(wǎng)盤文件上傳功能

通常情況下文件上傳可以這樣寫,每個(gè)待上傳的文件可以生成一個(gè)upload實(shí)例,然后實(shí)現(xiàn)自己的上傳操作。

let id=0

window.startUpload=function(uploadType,files){
  for(let i=0,file;file=files[i++];){
    let uploadObj=new Upload(uploadType,file.fileName,file.fileSize)
    uploadObj.init(id++)
  }
}

const Upload=function(uploadType,fileName,fileSize){
  this.uploadType=uploadType
  this.fileName=fileName
  this.fileSize=fileSize
  this.dom=null
}

Upload.prototype.init=function(id){
  let that=this
  this.id=id
  this.dom=document.createElement('div')
  this.dom.innerHTML='<span>文件名稱:'+ this.fileName +', 文件大小: '+ this.fileSize +'</span>' +'<button class="delFile">刪除</button>'
  this.dom.querySelector('.delFile').onclick=function(){
    that.delFile()
  }
  document.body.appendChild(this.dom)
}

Upload.prototype.delFile=function(){
  if(this.fileSize<3000){
    return this.dom.parentNode.removeChild(this.dom)
  }
  if(window.confirm('確定要?jiǎng)h除該文件嗎?'+this.fileName)){
    return this.dom.parentNode.removeChild(this.dom)
  }
}

startUpload( 'plugin', [
  {
      fileName: '1.txt',
      fileSize: 1000
  },
  {
      fileName: '2.html',
      fileSize: 3000
  },
  {
      fileName: '3.txt',
      fileSize: 5000
  }
]);

startUpload( 'flash', [
  {
      fileName: '4.txt',
      fileSize: 1000
  },
  {
      fileName: '5.html',
      fileSize: 3000
  },
  {
      fileName: '6.txt',
      fileSize: 5000
  }
]);

但這樣問題也很明顯,待上傳文件列隊(duì)如果有2000個(gè)文件,那么就要生成2000個(gè)upload實(shí)例,這無疑是很小號(hào)內(nèi)存的。

享元模式重構(gòu)文件上傳

在文件上傳的例子里,upload對(duì)象必須依賴uploadType屬性才能工作,這是因?yàn)椴寮蟼?、Flash上傳、表單上傳的實(shí)際工作原理有很大的區(qū)別,它們各自調(diào)用的接口也是完全不一樣的,必須在對(duì)象創(chuàng)建之初就明確它是什么類型的插件,才可以在程序的運(yùn)行過程中,讓它們分別調(diào)用各自的start、pause、cancel、del等方法。

let Upload = function (uploadType) {
  this.uploadType = uploadType
}

Upload.prototype.delFile = function (id) {
  uploadManager.setExternalState(id, this)

  if (this.fileSize < 3000) {
    return this.dom.parentNode.removeChild(this.dom)
  }

  if (window.confirm('確定要?jiǎng)h除該文件嗎? ' + this.fileName)) {
    return this.dom.parentNode.removeChild(this.dom)
  }
}

const UploadFactory = (function () {
  let createdFlyWeightObjs = {}
  return {
    create: function (uploadType) {
      if (createdFlyWeightObjs[uploadType]) {
        return createdFlyWeightObjs[uploadType]
      }
      return createdFlyWeightObjs[uploadType] = new Upload(uploadType)
    }
  }
})()

const uploadManager = (function () {
  let uploadDatabase = {}

  return {
    add: function (id, uploadType, fileName, fileSize) {
      let flyWeightObj = UploadFactory.create(uploadType)

      let 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,
        fileSize,
        dom
      }
      return flyWeightObj
    },
    setExternalState:function(id,flyWeightObj){
      let uploadData=uploadDatabase[id]
      for(let i in uploadData){
        flyWeightObj[i]=uploadData[i]
      }
    }
  }
})()

let id=0

window.startUpload=function(uploadType,files){
  for(let i=0,file;file=files[i++];){
    let uploadObj=uploadManager.add(++id,uploadType,file.fileName,file.fileSize)
  }
}

startUpload( 'plugin', [
  {
      fileName: '1.txt',
      fileSize: 1000
  },
  {
      fileName: '2.html',
      fileSize: 3000
  },
  {
      fileName: '3.txt',
      fileSize: 5000
  }
]);

startUpload( 'flash', [
  {
      fileName: '4.txt',
      fileSize: 1000
  },
  {
      fileName: '5.html',
      fileSize: 3000
  },
  {
      fileName: '6.txt',
      fileSize: 5000
  }
]);

使用享元模式后,無論有多少待上傳文件,也只會(huì)生成兩個(gè)upload對(duì)象。

享元模式的實(shí)用性

享元模式是一種很好的性能優(yōu)化方案,但它也會(huì)帶來一些復(fù)雜性的問題,從前面兩組代碼的比較可以看到,使用了享元模式之后,我們需要分別多維護(hù)一個(gè)factory對(duì)象和一個(gè)manager對(duì)象,在大部分不必要使用享元模式的環(huán)境下,這些開銷是可以避免的。

享元模式帶來的好處很大程度上取決于如何使用以及何時(shí)使用,一般來說,以下情況發(fā)生時(shí)便可以使用享元模式。

  • 一個(gè)程序中使用了大量的相似對(duì)象。
  • 由于使用了大量對(duì)象,造成很大的內(nèi)存開銷。
  • 對(duì)象的大多數(shù)狀態(tài)都可以變?yōu)橥獠繝顟B(tài)。
  • 剝離出對(duì)象的外部狀態(tài)之后,可以用相對(duì)較少的共享對(duì)象取代大量對(duì)象。

可以看到,文件上傳的例子完全符合這四點(diǎn)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容