11.Javascript設計模式之享元模式----Flyweight
GOF:運用共用技術有效地支援大量細粒度的對象。
享元模式概念解釋
享元模式:也就是說在一個系統中如果有多個相同的對象,那麼只共用一份就可以了,不必每個都去執行個體化一個對象。
比如說(這裡引用GOF書中的例子)一個文本系統,每個字母定一個對象,那麼大小寫字母一共就是52個,那麼就要定義52個對象。
如果有一個1M的文本,那麼字母是何其的多,如果每個字母都定義一個對象那麼記憶體早就爆了。
那麼如果要是每個字母都共用一個對象,那麼就大大節約了資源。
在Flyweight模式中,由於要產生各種各樣的對象,所以在Flyweight(享元)模式中常出現Factory模式。
Flyweight的內部狀態是用來共用的,Flyweight factory負責維護一個Object Storage Service池(Flyweight Pool)來存放內部狀態的對象。
Flyweight模式是一個提高程式效率和效能的模式,會大大加快程式的運行速度.應用場合很多。
享元模式樣本
下面列舉一個小汽車註冊的例子。
非最佳化的設計方式
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 = { getMake: function() { return this.make; }, getModel: function() { return this.model; }, getYear: function() { return this.year; }, transferOwnership: function(newOwner, newTag, newRenewDate) { this.owner = newOwner; this.tag = newTag; this.renewDate = newRenewDate; }, renewRegistration: function(newRenewDate) { this.renewDate = newRenewDate; }, isRegistrationCurrent: function() { var today = new Date(); return today.getTime() < Date.parse(this.renewDate); }};
在短時間內,這個註冊系統能夠進行正常工作,但是,當你所在的城市的人群逐漸增多,你會意識到這個系統會運行得越來越慢。
成千上萬的小汽車對象已經溢出了系統的可用資源,為了最佳化這個系統,使其長期穩定運行,我們需要藉助享元模式。
使用享元模式 第一.定義Car類
var Car = function(make, model, year) { this.make = make; this.model = model; this.year = year;};Car.prototype = { getMake: function() { return this.make; }, getModel: function() { return this.model; }, getYear: function() { return this.year; }};
第二.定義CarFactory
/* CarFactory singleton. */var CarFactory = (function() { var createdCars = {}; return { createCar: function(make, model, year) { // Check to see if this particular combination has been created before. if(createdCars[make + '-' + model + '-' + year]) { return createdCars[make + '-' + model + '-' + year]; } // Otherwise create a new instance and save it. else { var car = new Car(make, model, year); createdCars[make + '-' + model + '-' + year] = car; return car; } } };})();
第三.定義一個CarRecordManager
/* CarRecordManager singleton. */var CarRecordManager = (function() { var carRecordDatabase = {}; return { // Add a new car record into the city's system. addCarRecord: function(make, model, year, owner, tag, renewDate) { var car = CarFactory.createCar(make, model, year); carRecordDatabase[tag] = { owner: owner, renewDate: renewDate, car: car }; }, // Methods previously contained in the Car class. transferOwnership: function(tag, newOwner, newTag, newRenewDate) { var record = carRecordDatabase[tag]; record.owner = newOwner; record.tag = newTag; record.renewDate = newRenewDate; }, renewRegistration: function(tag, newRenewDate) { carRecordDatabase[tag].renewDate = newRenewDate; }, isRegistrationCurrent: function(tag) { var today = new Date(); return today.getTime() < Date.parse(carRecordDatabase[tag].renewDate); } };})();
這個估計得花點兒時間才能理解了,So do I...