javascript設計模式-享元模式(10)
阿新 • • 發佈:2018-12-25
享元模式是一種優化模式,它最適合解決因建立類似物件而涉及效能的問題。這種模式在js中尤其有用,因為複雜的js程式碼可能很快就會用光瀏覽器的所有可用記憶體。通過把大量獨立物件轉化為少量共享物件,可降低執行web應用程式所需的資源數量
傳統的多例項物件場景
//出廠商、型號、出廠日期、擁有者、車牌號、最近登記日期
var Car = function(make ,model , year , owner , tag , renewDate ){
this.make = make ;
this.model = model ;
this.year = year ;
this .owner = owner ;
this.tag = tag ;
this.renewDate = renewDate;
};
Car.prototype = {
constructor:Car ,
getMake :function(){
return this.make;
},
getModel:function(){
return this.model;
},
getYear:function(){
return this.year;
},
renewRegistration:function (newRenewDate){
this.renewDate = newRenewDate;
}
};
var arr = [] ;
var stime = new Date().getTime();
for(var i = 0 ; i < 5000000; i ++){
// runtime: 734ms web: 570
arr.push(new Car('上海大眾','邁騰','2012-02-03','bhx','bj0011','2013-04-01'));
}
var etime = new Date().getTime();
alert(etime - stime);
享元模式的改進
//享元模式:優化的設計模式 (優化:時間[程式碼的執行時間]、空間[web瀏覽器記憶體])
//享元模式:內在資料static (出廠商、型號、出廠日期) 外在資料(擁有者、車牌號、最近登記日期)
//出廠商、型號、出廠日期、擁有者、車牌號、最近登記日期
var Car = function(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
};
Car.prototype = {
constructor: Car,
getMake: function() {
return this.make;
},
getModel: function() {
return this.model;
},
getYear: function() {
return this.year;
}
};
//工廠模式(閉包工廠)
var CarFactory = (function() {
//用於承裝已經生產好的car
var createdCars = {};
return {
createCar: function(make, model, year) {
//如果createdCars物件裡已經存在當前的make ,model , year
if (createdCars[make + model + year]) {
return createdCars[make + model + year];
} else {
var car = new Car(make, model, year);
createdCars[make + model + year] = car;
return car;
}
}
};
})();
//單體模式(外在的資料 和內在的資料 結合在一起)
var CarRecordManager = (function() {
//把登記好的汽車放到這個物件裡
var carRecordDataBase = {};
return {
addCarRecord: function(make, model, year, owner, tag, renewDate) {
var car = CarFactory.createCar(make, model, year);
carRecordDataBase[tag] = {
owner: owner,
renewDate: renewDate,
car: car
};
},
renewRegistration: function(tag, newRenewDate) {
carRecordDataBase[tag].renewDate = newRenewDate;
}
};
})();
var arr = [];
var stime = new Date().getTime();
for (var i = 0; i < 5000000; i++) {
// runtime: 734ms web: 570
// arr.push(new Car('上海大眾','邁騰','2012-02-03','bhx','bj0011','2013-04-01'));
//享元模式的測試
// runtime: 300ms web: 230
arr.push(CarRecordManager.addCarRecord('上海大眾', '邁騰', '2012-02-03', 'bhx', 'bj0011', '2013-04-01'));
}
var etime = new Date().getTime();
alert(etime - stime);