javascript的享元模式(六)

享元(flyweight)模式是一種用於性能優化的模式,若是系統由於建立大量相似的對象而致使內存佔用太高,享元模式就很是有用了。在javascript中,瀏覽器特別是移動端的瀏覽器分配的內存並不算多,如何節省內存就成了一件很是有意義的事情。javascript

核心:提取對象中相同部分封裝成對象共享,減小對象的建立數量,來實現性能優化。java

// 有個汽車網站,裏面包含了不少汽車信息,須要動態加載,咱們通常會這麼作

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);
		}
	
	
	}


})()
相關文章
相關標籤/搜索