js40---享元模式
阿新 • • 發佈:2017-05-23
ext 北京 for arguments 性能 date logs 匿名 model
/** * 享元模式是一個為了提高性能(空間復雜度)的設計模式 * 他使用與程序會生產大量的相類似的對象是耗用大量的內存的問題 */ (function(){ /** * 制造商 * 型號 * 擁有者 * 車牌號碼 * 生產日期 */ 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; this.getMake = function(){ return this.make; } } var simpleProfiler2 = function(componet){//形參看成構造函數傳入的成員變量的值。函數名看成類名。this.看成成員屬性和成員方法。 this.componet = componet; this.action = function(methodName){ var self = this; var method = componet[methodName];//對象的成員方法可以用中括號獲取 if(typeof method == "function"){ var startDate = new Date().getTime(); method.apply(self.componet,arguments); var endDate = new Date(); alert(endDate- startDate); } } } //北京車兩 4150000 全部要登記 var ca = new Array(); function addCar(){ this.begin = function(){ for (var i = 0; i < 4150000; i++) { ca.push(new Car("東風","雪鐵龍","2012-4-8", "雲鳳程","京pcat2145","2012-2-13")); } } } new simpleProfiler2(new addCar()).action("begin") /** * extjs的開發下拉框,單選框 * 等小組件如果用享元模式 會非常的節省性能的開支 */ })()
/** * 享元模式是一個為了提高性能(空間復雜度)的設計模式 * 他使用與程序會生產大量的相類似的對象是耗用大量的內存的問題 */ (function(){ /** * 制造商 * 型號 * 擁有者 * 車牌號碼 * 生產日期 */ var Car = function(make,model,year){ ///共性屬性 this.make = make; this.model = model; this.year = year; this.getMake = function(){ return this.make; } } var carInfoFactory = (function(){//carInfoFactory代指內部函數、類,匿名函數執行,就相當於外部函數執行了一次,內部函數執行多次公用外部數據 var carInfo = {}; return function(make,model,year){ if(carInfo[make+model+year]){ return carInfo[make+model+year]; }else{ var newCar = new Car(make,model,year); carInfo[make+model+year] = newCar; return newCar; } } })(); //工廠 var myCarInfo = function(){ this.createCar = function(make,model,year,owner,tag,renewDate){ var c = carInfoFactory(make,model,year);//外部函數,利用閉包,調用多次減少了new的時間 //特性不同的屬性 c["owner"] = owner; c["tag"] = tag; c["renewDate"] = renewDate; return c;//返回的是地址,同一個對象 } } var test = new myCarInfo();//工廠對象只有一個 var startDate = new Date().getTime(); var ca = new Array(); for (var i = 0; i < 5; i++) { ca.push(test.createCar("東風","雪鐵龍","2012-4-8", "雲鳳程","京pcat2145","2012-2-13"))//生產車的方法調了4150000次 } var endDate = new Date(); alert(endDate - startDate); for(arr in ca){ alert(ca[arr].make + "--" +ca[arr].renewDate) } })()
js40---享元模式