享元(flyweight)模式是一種用于性能優(yōu)化的模式,“fly”在這里是蒼蠅的意思,意為蠅量級。享元模式的核心是運用共享技術(shù)來有效支持大量細(xì)粒度的對象。
如果系統(tǒng)中因為創(chuàng)建了大量類似的對象而導(dǎo)致內(nèi)存占用過高,享元模式就非常有用了。在JavaScript中,瀏覽器特別是移動端的瀏覽器分配的內(nèi)存并不算多,如何節(jié)省內(nèi)存就成了一件非常有意義的事情。
網(wǎng)盤文件上傳功能
通常情況下文件上傳可以這樣寫,每個待上傳的文件可以生成一個upload實例,然后實現(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('確定要刪除該文件嗎?'+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
}
]);
但這樣問題也很明顯,待上傳文件列隊如果有2000個文件,那么就要生成2000個upload實例,這無疑是很小號內(nèi)存的。
享元模式重構(gòu)文件上傳
在文件上傳的例子里,upload對象必須依賴uploadType屬性才能工作,這是因為插件上傳、Flash上傳、表單上傳的實際工作原理有很大的區(qū)別,它們各自調(diào)用的接口也是完全不一樣的,必須在對象創(chuàng)建之初就明確它是什么類型的插件,才可以在程序的運行過程中,讓它們分別調(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('確定要刪除該文件嗎? ' + 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
}
]);
使用享元模式后,無論有多少待上傳文件,也只會生成兩個upload對象。
享元模式的實用性
享元模式是一種很好的性能優(yōu)化方案,但它也會帶來一些復(fù)雜性的問題,從前面兩組代碼的比較可以看到,使用了享元模式之后,我們需要分別多維護(hù)一個factory對象和一個manager對象,在大部分不必要使用享元模式的環(huán)境下,這些開銷是可以避免的。
享元模式帶來的好處很大程度上取決于如何使用以及何時使用,一般來說,以下情況發(fā)生時便可以使用享元模式。
- 一個程序中使用了大量的相似對象。
- 由于使用了大量對象,造成很大的內(nèi)存開銷。
- 對象的大多數(shù)狀態(tài)都可以變?yōu)橥獠繝顟B(tài)。
- 剝離出對象的外部狀態(tài)之后,可以用相對較少的共享對象取代大量對象。
可以看到,文件上傳的例子完全符合這四點。