享元模式之各版本
//-------普通穿衣服版--------------- class Model { constructor(sex, cloth) { this.sex= sex; this.cloth= cloth; } takePhoto(){ console.log( 'sex= ' + this.sex + ' underwear=' + this.cloth) } } for(let i=0 ; i<100 ; i++ ){ let man= new Model('man','男士衣服'+i); man.takePhoto(); let woman= new Model('woman','女士衣服'+i); woman.takePhoto(); } //-------普通穿衣服享元版--------------- console.log('---------------普通穿衣服享元版---------------'); class Model2 { constructor(sex) { this.sex= sex; } takePhoto(){ console.log( 'sex= ' + this.sex + ' underwear=' + this.cloth) } }; const nan = new Model2('nan');//问题一 对象没有用到就创建了,时机不对,用factory 解决 const nv = new Model2('nv'); for(let i=0 ; i<100 ; i++ ){ nan.cloth='男士衣服'+i; // 问题二 对象外部状态 从外部添加 需要用管理器解决 nan.takePhoto(); nv.cloth='女士衣服'+i; nv.takePhoto(); }
高级版
let id = 0; let startUpload = function (uploadtype, files) { for ( let i = 0, file; file = files[ i++ ]; ){ UploadManager.add(++id,uploadtype,file.fileName,file.fileSize); } } let UploadManager = (function () { let outerstate = {}; return{ add(id ,uploadtype, fileName,fileSize){ let uploadObj = UploadFactory.create(uploadtype); let dom = document.createElement( 'div' ); dom.innerHTML = `<span>文件名称:${fileName}, 文件大小: ${fileSize} </span> <button class="delFile">删除</button>`; dom.querySelector( '.delFile' ).onclick = function(){ uploadObj.delFile( id ); } document.body.appendChild( dom ); outerstate[ id ] = { fileName: fileName, fileSize: fileSize, dom: dom }; }, setExternalState: function( id, flyWeightObj ){ let uploadData = outerstate[ id ]; for ( let i in uploadData ){ flyWeightObj[ i ] = uploadData[ i ]; } } } })() let UploadFactory = (function () { let createdFlyWeightObjs = {}; return{ create(uploadtype){ if(createdFlyWeightObjs[uploadtype]){ return createdFlyWeightObjs[uploadtype] } return createdFlyWeightObjs[uploadtype] = new Upload(uploadtype); } } })() class Upload{ constructor(uploadtype){ this.uploadtype = uploadtype } delFile(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 ); } } } 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 } ]);
最终版 用es6 +webpack 模块分割,
详见 https://github.com/KuiShang/flyWeight_es6