享元是意译,英文为 flyWeigth。fly 苍蝇 weight 重量 = 轻量
享元可以理解为通用的属性和元方法,即通过共享属性的方式来达到减少创建对象的目的。从而提升性能优化。
例子
// 100 套衣服,男女各 50 套衣服 进行拍照
var Modal = function(sex, clothes) {
this.sex = sex;
this.clothes = clothes;
}
Modal.prototype.takePhoto = function() {
console.log("sex =" + this.sex + "衣服:" + this.clothes);
}
for (var i = 0; i < 50; i++) {
var modal = new Modal("male", "clothes" + i); // 实现了 50 个男模特
modal.takePhoto();
}
for (var j = 0; j < 50; j++) {
var modal = new Modal("female", "clothes" + j); // 实现了 50 个女模特
modal.takePhoto();
}
// --------------------------------------------------------------
var Modal = function(sex) {
this.sex = sex;
}
Modal.prototype.takePhoto = function() {
console.log("sex =" + this.sex + "衣服:" + this.clothes);
}
var maleModal = new Modal("male");
var femaleModal = new Modal("female");
for (var i = 0; i < 50; i++) {
maleModel.clothes = i; // 问题在于这种赋值相当隐晦,表意不明显。
// 以为是普通对象,实则是实例对象
// 动态增加外部状态
maleModel.takePhoto();
}
for (var j = 0; j < 50; j++) {
femaleModel.clothes = j;
femaleModel.takePhoto();
}
享元模式
解决上面的两个问题,使其有控制。
var Modal = function(sex) {
this.sex = sex;
}
Modal.prototype.takePhoto = function() {
console.log("sex =" + this.sex + "衣服" + this.clothes);
}
var modeFactory = (function() {
var modalGender = {};
// 单例模式,保证一个性别只有一个实例对象
return {
createModel: function(sex) {
if(modalGender[sex]) {
return modalGender[sex];
}
return (modalGender[sex] = new Modal(sex));
}
};
})();
// 状态管理器
var ModalManager = (function() {
const modalObj = {};
return {
add: function(sex, i) {
modalObj[i] = {
clothes: "衣服:" + i
};
},
setExternalState: function(modal, i){
modal.clothes = modalObj[i].clothes;
}
};
})();
for (var i = 0; i < 50; i++) {
var maleModal = ModalManager.add("male", i);
ModalManager.setExternalSate(maleModal, i);
maleModal.takePhoto();
}
for (var i = 0; i < 50; i++) {
var femaleModal = ModalManager.add("female", i);
ModalManager.setExternalSate(femaleModal, i);
femaleModal.takePhoto();
}