享元(flyweight)模式是一种用于性能优化的模式,如果系统因为创建大量类似的对象而导致内存占用过高,享元模式就非常有用了。在javascript中,浏览器特别是移动端的浏览器分配的内存并不算多,
享元(flyweight)模式是一种用于性能优化的模式,如果系统因为创建大量类似的对象而导致内存占用过高,享元模式就非常有用了。在javascript中,浏览器特别是移动端的浏览器分配的内存并不算多,如何节省内存就成了一件非常有意义的事情。
核心:提取对象中相同部分封装成对象共享,减少对象的创建数量,来实现性能优化。
// 有个汽车网站,里面包含了很多汽车信息,需要动态加载,我们一般会这么做var Car = function(brand, model, owner, carID, renewDate){ this.brand = brand; //品牌 this.model = model; //型号 this.owner = owner; //车主 this.carID = carID; //车牌号 this.renewDate = renewDate; //注册日期}Car.prototype = { getBrand: function () { return this.brand; }, getModel: function () { return this.model; }, transferOwnership: function (newOwner, carID, newRenewDate) { // 转手 this.owner = newOwner; this.carID = carID ; this.renewDate = newRenewDate; }, renewRegistration: function (newRenewDate) { // 重新注册 this.renewDate = newRenewDate; }, isRegistrationCurrent: function () { //注册是否过期 var today = new Date(); return today.getTime() < Date.parse(this.renewDate); }}// new 了很多对象后,性能明显下降
享元模式重构:
//享元模式// 同一个牌子和型号的车不少吧?车都可以看到牌子和型号吧?所以公共出来var Car = function (brand,model) { this.brand = brand; this.model = model;};Car.prototype = { getBrand: function () { return this.brand; }, getModel: function () { return this.model; }};var CarFactory = (function(){ var createdCars = []; return { createdCar: function(brand, model){ if(!createdCars[brand + model]){ createdCars[brand + model] = new Car(brand, model); } return createdCars[brand + model]; } }})();var CarRecordManager = (function(){ var carRecordDatabase = {}; return { addCarRecord:function(brand, model, owner, carID, renewDate) { carRecordDatabase[carID] = { car: CarFactory.createdCar(brand, model), owner: owner, carID: carID, renewDate: renewDate } }, transferOwnership: function (newOwner, carID, newRenewDate) { // 转手 carRecordDatabase[carID] = { owner: newOwner; carID: carID ; renewDate: newRenewDate; } }, renewRegistration: function (carID, newRenewDate) { // 重新注册 carRecordDatabase[carID].renewDate = newRenewDate; }, isRegistrationCurrent: function (carID) { //注册是否过期 var today = new Date(); return today.getTime() < Date.parse(carRecordDatabase[carID].renewDate); } }})()