javascript設計模式實現(xiàn)源碼剖析_第1頁
javascript設計模式實現(xiàn)源碼剖析_第2頁
javascript設計模式實現(xiàn)源碼剖析_第3頁
javascript設計模式實現(xiàn)源碼剖析_第4頁
javascript設計模式實現(xiàn)源碼剖析_第5頁
免費預覽已結束,剩余351頁可下載查看

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

<!doctype<html<metacharset="UTF-<title>8**********但是抽象工廠著重的就是為一個產品簇選擇實現(xiàn),定義在抽象工廠里面**1.*******3.*2.*****44**48var Factory=function()Ftotype= *示例方法,創(chuàng)建抽象產品A *@return{[type]}抽象產品A createProductA:function() //創(chuàng)建抽象產品 createProductB:function()586061*A,BProductAProductAProductB64ProductB66//AAvarProductA1=function(){};ProductA1.prototype=Object.create(71//varProductA2=varProductA2=function()ProductA2.prototype=75//

function()function()77//產品BvarProductB1=varProductB1=function()ProductB1.prototype=80//varProductB2=varProductB2=function()ProductB2.prototype=84//86varConcretFactory1=function()ConcretFtotype= ConcretFtotype.createProductA=function()returnnew93ConcretFtotype.createProductB=function()returnnew96function()varConcretFactory2function()varConcretFactory2ConcretFtotypeConcretFtotype function()newfunction()newConcretFtotype.createProductBnewConcretFtotype.createProductAfunction()function()varvarafnewvarAMDCPU=function{this.id=116varMSIMainboard=function{this.id=id;

pi:function()returnnewStotype=function()varSchema1 createMainboardApi:function()128 129

new

varSchema2Schema2=

function()pi:function()new136 createMainboardApi:function()138 139

newvarComputerEngineer=(function()varvarfunctionprepareHardWare(schema)cpu= mainboard= varComputerEngineervarComputerEngineercpu=mainboard=ComputerEtotype=puter:function(schema)function() 158 159 return162varengineervarengineernewvarschemanewengineerengineer=schema functionEmployee(name)functionEmployee(name)=log.add("Iamemployeelog.add("Iamemployeefunction()this.say177functionfunction

{

++=function(name)=

}

new185functionVendor(name) =

this.say

function()

log.add("Iamvendor

+190=192function=

{

function(name)

new196//log//logvarlog=(function{varlog="";return{add:function(msg){log+=msg+show:function(){log=}

"\n"; 208211function{ s s=varvaremployeeFactory=newvarvendorFactory=news.push(employeeFactory.create("Joans.push(employeeFactory.create("Joans.push(employeeFactory.create("Tim s.push(vendorFactory.create("Geralds.push(vendorFactory.create("Geralds.push(vendorFactory.create("Nicole 0,len0,len s.length;i<len;i++)

for(vari }<!doctype<html<metacharset="UTF-<title>模式8 *10******** *要實現(xiàn)同樣的構建過程可以創(chuàng)建不同的表現(xiàn),那么一個自然的思路就是先把構建過程獨立出來,在模式中把它稱為指導者,由它來指導裝配過程,但步的對象,在模式中稱這些實現(xiàn)對象為。*是可以被切換的**主要功能是構建復雜的產品,而且是細化的,分步驟的構建產品,也就是模式中在一步一步解決構造復雜對象的問題。更為重要的是,這個構建的過程是統(tǒng)一的,固定不變的,變化的部分放到*模式的重心在于分離構建算法和具體的構造實現(xiàn),從而使得構建*模式的時候,可以讓客戶端創(chuàng)模式的時候,可以讓客戶端創(chuàng)造Director,在Director里封裝整體在、構建算法,然后讓Director去調用Builder,讓Builder來封*應**去操作的情況,就是讓客戶端和Director融合起來,讓客戶端***1.*****2.42 45varBuilder=function(){ var//獲//獲 this.getResult=return52 this.buildPart=56 57////指導者,指導使 //傳 對61varDirector= this.builder=6364Dtotype={66 construct: 68 6971 varBuilder= Btotype=//構建輸出文件的Header部分 buildHeader:function(ehm){}, buildBody: buildFooter:function(efm){} 對 varTxtBuilder=this.stringBuffer= TxtBtotype=proto: buildBody:vartblName,for(tblNameinmapData)this.stringBuffer+=tblName+"\n";for(edminmapData[tblName])this.stringBuffer+=edm.getProductId()+','+98 edm.getPrice()+','+edm.getAmount()+99 } buildFooter:this.stringBuffer+=104 buildHeader:this.stringBuffer+=ehm.getDepId()+','+ ehm.getExportDate()|'\n'; getResult:returnnewBuffer(this.stringBuffer); 112 varXmlBuilder=this.stringBuffer= XmlBtotype=proto:buildHeader:buildHeader: getResult:

varDirector=//傳varDirector=//傳 對

Dtotype= construct:function(ehm,mapData,efm){

vartextBuilder

new

vardirector

new

director.construct(ehm,mapData,

varxmlBuilder

new

vardirector2

new

director2.construct(ehm,mapData,148 150 11 實際上在Builder接口的實現(xiàn)中,每個部件構建的方法里面,除了部件裝配再進一步,如果在實現(xiàn)Builder的時候,只有創(chuàng)建對象的功能,而沒有組裝的功能。那么這個時候的Builder實現(xiàn)跟抽象工廠的實現(xiàn)是類似的。類似于具體的工廠,而且Builder接口里面定義的創(chuàng)建各個部件的方法也是有關聯(lián) 才會調 1641643.165171171174了,但是指導者是不負責具體的部件創(chuàng)建和組裝的,因此客戶端是從this.contractId=this.contractId=varInsuranceContractvarInsuranceContract=191

Name=panyName this.beginDate=builder.getBeginDate();this.endDate=builder.getEndDate();this.otherDate=builder.getOtherDate();

InsuranceCtotype={someOperation:function(){console.log('NowinInsuranceContractsomeOperation=' 196198

varConcreteBuilderthis.contractId

function(contractId,beginDate,203

this.beginDate=beginDate;this.endDate=endDate;

ConcreteBtotype= Name: Name

panyName:panyName=

setOtherDate:this.otherData=

getContractId:

Name:

panyName:

getBiginDate:

{

function(){returnfunction(){ build:thrownewError('

var

Name Name.trim().length>

pany=panyName.trim().length>0;

panyNamepany)247

newError(' && pany)

newError('if(this.beginDate<=0)

newError('if(this.endDate<=0)

newError('if(this.endDate<=this.beginDate)

newError(' 267

newInsuranceContract.ConcreteBuilder=ConcreteBuilder;return276varbuilder=newInsuranceContract.ConcreteBuilder('001',123456,277varcontract 278281282 286287Builder 個產品簇;而模式的主要目的是按照構造算法,一步一步來構建一個復雜的產品對象,桐城要等到整個構建過程沒才會得到最終的產品對象。組合使用:在Builder來實現(xiàn)。有抽象工廠模式負責部件對象創(chuàng)建,Builder 實現(xiàn)。 模式Director用來定義整體的構建算法,把算法中某些涉及到具體部件對象的創(chuàng)建和裝配功能,委托給具體的Builder來實現(xiàn)。3003011).目的: 3022)。實現(xiàn) 3033)。復雜度:DirectorBuilder 309312//http:/ 314functionShop() this.construct={

returnbuilder.get();320functionCarBuilder()this.car=this.step1=function()this.car=new326 this.step2=function()329 this.get=function()return332 333functionTruckBuilder()this.truck=this.step1=function()this.truck=new339 this.step2=function()342 this.get=function()return345 346functionCar()this.doors=this.addParts=function()this.doors=352 this.say=function() log.add("Iama"+this.doors+"-doorcar"); 356functionTruck()this.doors=this.addParts=function()this.doors=362 this.say=function() log.add("Iama"+this.doors+"-doortruck"); }//logvarlog=(function()varlog=return add:function(msg){log+=msg+"\n"; show:function(){alert(log);log=""; 375functionrun()varshop=newShop();varcarBuilder=newvarcar=shop.construct(carBuilder);vartruck=shop.construct(truckBuilder);varvarcar=shop.construct(carBuilder);vartruck=shop.construct(truckBuilder);390<!doctype<html<metacharset="UTF-89*********定義*定義類2223*25**名建議**口名稱/*/*BycycleShopclassvarvarBicycleShopBicycleStotypeBicycleStotype=sellBicycle:sellBicycle:function(model)bicyclebicyclebicyclebicyclebicyclebicycle}}

functionfunction()varswitch(model)'Thenewvarswitch(model)'Thenew'Thenew'TheComfortnewreturnsellBicycle法根據(jù)所要求的自行switch句創(chuàng)建一個自行車的實例。各種型號的自行車實例可以互換使用,因為它們都實現(xiàn)了Bicycle接口.接口在工廠模式中起著很重要的作用。如果不對對象進行某種類型檢查以確保其實現(xiàn)了必須的方法,/*SpeedsterclassvarSpeedster=function()//implementsStotypeStotype=assemble:assemble:function()wash:wash:function()ride:ride:function()repair:repair:function()}}arcaliforniaCruisers=newvaryourNewBike=californiaCruisers.sellBicycle('TheSpeedster');83 把方/*BicycleFactorynamespacevarBicycleFactory= createBicycle:function(model)varswitch(model)case'The bicycle=new

'The96 bicycle=new

'The101 biccle=new

'TheComfortbicyclebicycle107

return110 111113方 115116/*BicycleShopclass,improved117varBicycleShop=function()118119BicycleStotype=120 sellBicycle:function(model) varbicycle=BicycleFactory.createBicycle(model);123 124 return127 128129130BicycleFactory 131132133134136137139141框架能干什么1431.1442146***定義*定義定定159160*** 162 164 166168 170171/*BicycleShopclass )172varBicycleShop=function()173174BicycleStotype=175 sellBicycle:function(model) varbicycle=this.createBicycle(model);178 179 return182 183 createBicycle:function(model) thrownewError('Unsupportedoperationon class.');185 186functionextend(subClass,functionextend(subClass,superClass)functionfunctionF()194 196 F.prototype=197 subCtotype=new198 subCtotype.constructor=subClass;200 subClass.superclass=superCtotype;if(superCtotype.constructor===Ototype.constructor) superCtotype.constructor= }/*AcmeBicycleShopclassvarAcmeBicycleShop=function()extend(AcmeBicycleShop,AcmeBicycleStotype.createBicycle=function(model)varswitch(model)case'The bicycle=newnewcase'Thenew

bicycle

case'TheComfort 222 bicycle=new223 224 Interface.ensureImplements(bicycle, return226228/*GeneralProductsBicycleShopclassvarvarGeneralProductsBicycleShopextend(GeneralProductsBicycleShop,extend(GeneralProductsBicycleShop,bicyclebicyclebicyclebicyclebicyclebicycle}}248249

functionfunction()function(model)varswitch(model)'Thefunction(model)varswitch(model)'Thenew'Thenew'TheComfortnewreturnAcme或GeneralProducts自行車專賣店。251252varalecsCruisers=new253varyourNewBike=alecsCruisers.sellBicycle('TheLowrider');255varbobsCruisers=new256varyourSecondNewBike=bobsCruisers.sellBicycle('TheLowrider');258 260262263265*266如果需要像前面自行車的例子一樣,創(chuàng)建一些用不同方式實現(xiàn)同一接口的對象,那么可以使用一個工*省設置 272*275278例:XHRActiveXObject280281/*AjaxHandlerinterface282varAjaxHandler=newInterface('AjaxHandler',['request','createXhrObject']);284/*SimpleHandlerclass285varSimpleHandler=function()286 //implements287SimpleHtotype=288 request:function(method,url,callback,{ arxhr= xhr.onreadystatechange=function()if(xhr.readyState!=={ ((xhr.status>=200&&xhr.status<300)||xhr.status===304) callback.success(xhr.responseText,xhr.responseXML) xhr.open(method,url,if(method!=='POST') postVars=}}////FactorycreateXhrObject:function()varvarmethods=functionfunction()newnewfunctionfunction()newnewfunctionfunction()newnewfunctionfunction()newnew for(vari=0,len=methods.length;i<len;i++)try }catch(e) //ifwereachthispoint,method[i]this.createXhrObject= //Memoizethereturn //ifwereachthispoint,noneofthemethods thrownewError('SimpleHandler:CouldnotcreateanXHR333 334336 338varmyHandlervarmyHandlernewvarvarcallback=success:success:function(responseText)++failure:functionfailure:function(statusCode)+myHandler.request('GET',myHandler.request('GET','script.php',對對則/*/*QueueHandlerclassvarQueuedHandler=function()//implementsthis.queue this.requestInProgress this.retryDelaythis.retryDelay//In extend(QueuedHandler,extend(QueuedHandler,****@param{Boolean}overridefunction(method,function(method,url,callback,postVars,override)QueuedHtotype.request!override)if!override)if(this.requestInProgressmethod:method:url:url:callback:callback:postVars:postVars:}}elsethisthis.requestInProgressvarvarxhr=varvarthatfunction()function()xhr.onreadystatechange4)4)if(xhr.readyState if((xhr.status>=200&&xhr.status<300)||xhr.status===304) }else setTimeout(function() that.request(method,url,callback,postVars, },that.retryDelay* xhr.open(method,url,if(method!=='POST') postVars= QueuedHtotype.advanceQueue=function()if(this.queue.length===0)this.requestInProgress= varreq=this.request(req.method,req.url,req.callback,req.postVars,415417418QueueHandlerrequestSimpleHandler419421/*OfflineHandlerclass422varOfflineHandler=function() //implements this.storedRequests=extend(OfflineHandler,extend(OfflineHandler,function(method,function(method,url,callback,postVars)ifif(XhrManager.isOffline())////Storetherequestsuntilwearemethod:method:url:url:callback:callback:postVars:postVars:}}else////CallSimpleHandler'srequestmethodifweareOfflineHandler.superclass.request(method,OfflineHandler.superclass.request(method,url,callback,function()function()this.storedRequests.length;ithis.storedRequests.length;i<len;i++)0,lenfor(varivarvarreq /*/*XhrManagersingletonvarvarXhrManager=createXhrHandler:createXhrHandler:function()varvarifif(this.isOffline())newnewxhrif(if(this.isHighLatency())}newnewxhr}}elsenewnewxhr}}Interface.ensureImplements(xhr,Interface.ensureImplements(xhr,returnreturntest:test:function()this.timerthis.timer=this.timeoutthis.timeoutvarthatvarthatnewnewvarmyHandlervarcallbackvarcallbacksuccess:success:function(responseText)++failure:failure:function(statusCode)++}}this.timerthis.timer=window.setTimeout(that.test,myHandler.request('GET',myHandler.request('GET','script.php',isOffline:isOffline:function()////DoaquickrequestwithSimpleHandler////seeifitisHighLatency:isHighLatency:function()//Do//DoaseriesofrequestswithSimpleHandler//time//timetheresponses.Bestdoneonce,as//branching//branching}}varvarmyHandler=varvarcallback=success:success:function(responseText)++alert('Success:+alert('Failure:+alert('Failure:failure:function(statusCode)}}myHandler.request('GET',myHandler.request('GET','script.php',508方方這510512513514工廠模式的主要好處在于消除對象間的耦合。通過使用工廠方法而不是new關鍵字及具體類。你可以 515所有這些好處都與面向對象涉及的這兩條原則有關:弱化對象間的耦合;防止代碼的重用。這些都有516518519520如果根本不可能另外換用一個類,或者不需要在運行期間在一系列可互換的類中進行選擇,那就不應可以一眼就看到調用的是什么構造函數(shù),而不必去查看某個工廠方法以便知道實例化的是什么類。工廠 521523524526*527528簡單工廠使用來選擇實現(xiàn)的,可以選擇任意接口的實現(xiàn)。一個簡單工廠可以有多個用于選擇并創(chuàng)建對529抽象工廠模式使用來選擇產品簇的實現(xiàn)的,也就是說一般抽象工廠里面有多個用于選擇并創(chuàng)建對象的 532*533534工廠方法的本質也使用來選擇實現(xiàn)的,跟簡單工廠的區(qū)別在于工廠方法是把選擇具體實現(xiàn)的功能延遲537****/*/*AjaxHandlerinterfacenewInterface('AjaxHandler',newInterface('AjaxHandler',['request',varAjaxHandler/*SimpleHandler/*SimpleHandlerclassfunctionvarfunctionvarSimpleHandler////implementsSimpleHtotypeSimpleHtotype=request:request:function(method,url,callback,postVars)varvarxhrfunction()function()xhr.onreadystatechange4)4)if(xhr.readyState}}304)300)||304)300)||xhr.status&xhr.status((xhr.statuscallback.success(xhr.responseText,callback.success(xhr.responseText,xhr.responseXML)'POST')if'POST')if(methodxhr.open(method,url,postVarspostVars}}createXhrObject:functioncreateXhrObject:function()//Factoryvarmethods=functionfunction()newnewfunctionfunction()newnewfunctionfunction()newnew}582 for(vari=0,len=methods.length;i<len;i++)try }catch(e) //ifwereachthispoint,method[i]this.createXhrObject= //Memoizethereturn //ifwereachthispoint,noneofthemethods thrownewError('SimpleHandler:CouldnotcreateanXHR597 598function$()varelements=for(vari=0;i<arguments.length;i++)varelement= element if(typeofelement== element 606 if(arguments.length===1) return609 610 611 return613615 616617 618/*DisplayModuleinterface619varDisplayModule=newInterface('DisplayModule',['append','remove','clear']);621/*ListDisplayclass.622varListDisplay=function(id,parent) //implementsthis.listthis.listthis.list.idthis.list.id=ListDtotypeListDtotype=append:append:function(text)varvarnewElnewEl.innerHTMLnewEl.innerHTML=returnreturnremove:remove:function(el)clear:clear:function()this.list.innerHTMLthis.list.innerHTML}}配配/*/*Configurationvarvarconf=id:id:'cnn-top-feedUrl:feedUrl:updateInterval:updateInterval:60,//Inparent:parent:$('feed-上/*/*FeedReaderclass.varvarFeedReader660

functionfunction(display,xhrHandler,conf)this.displaythis.display=this.xhrHandler=this.conf=661FeedRtotype=662 fetchFeed:function() varthat= varcallback=665 success:function(text,xml)666 that.parseFeed(text,failure:failure:function(status)674 675 parseFeed:function(responseText,responseXML)

+ varvaritems= vartitle= for(vari=0,len=items.length;ivartitle= varvarlink= this.display.append('<ahref="'+link.firstChild.data+'">'+title.firstChild.data+'"</a>'); showError:function(statusCode)this.display.append('Errorfetching687 stopUpdates:function() startUpdates:function()varthat=erval=setInterval(function() },this.conf.updateInterval* /*FeedManagernamespacevarFeedManager= createFeedReader:function(conf)vardisplayModule=newListDisplay(conf.id+'-display',varsimpleHandler=newnewFeedReader(displayModule,xhrHandler,varxhrHandlernewFeedReader(displayModule,xhrHandler, 709 710713/*Title:Factory714Description:createsobjectswithoutspecifyingtheexactclassto715716varjsp=717jsp.dom=718jsp.dom.Text=function()vartxt this.insertvartxt 721 722 723724jsp.dom.Link=function()varlink this.insert=functionvarlink 727 link.href 729 730 731732jsp.dom.Image=function()varim this.insert=functionvarim735 im.src=736 737 738739jsp.dom.factory=function(type) returnnew741743varo=744.url= 工廠方法模式與IoCIocInversionofControlDIDependencyInjection,

而而 778781varA=function() this.c=783784A.prototype=785 setC:function(c) this.c=788 789 t1:function() 792 793795varC=function()796797C.prototype.tc=function()798 console.log('instanceC799801(newA()).setC(newC()).t1();廠varA=function()A.prototype= createC1:function() t1:function() varA2=function()816817extend(A,818A2.prototype.createC1=function() returnnew820823//http:/ 825(function() functionFactory() this.createEmployee=function(type) var if(type==="fulltime")831 employee=newif(type832 }if(type833 employee=new834 }elseif(type==="temporary")

employee }employee employee

newTemporary();if(typeif(type==="contractor")

employee.type= employee.say=function() log.add(this.type+":rate"+this.hourly return

845 847 varFullTime=function()851

this.hourly= varPartTime=function()854

this.hourly= varTemporary=function() this.hourly=857 varContractor=function() this.hourly=860 //logvarlog=(function()varlog=return add:function(msg) log+=msg+ show:function() log= function{ varemployees=[]; varfactory=newFactory();883 884 885 886 for(vari=0,len=employees.length;i<len;i++)889 890 892 893 894897898899<!DOCTYPE<metacharset="utf-*器模**將一個類的接口轉換成客戶希望的另外一個接口。適配器模式使得原本由于接口不兼容而不能一起 **一***22*22*不可應應*2626*varvarAdaptee35varAdapter=this.adaptee=41Atotype= request://do//other 51varadaptee=new52vartarget=new5355 6062適配器的實現(xiàn)方式其實是依靠對象組合的方式。通過給適配器對象組合被適配的對象,然后當客戶端Target的時候,適配器會把相應的功能委托給被適配對象去完成。6466target--Adapter--676970具體實現(xiàn)里面調用Adaptee。也就是說適配器通常是一個Target類型,而不是Adaptee類型。74 83適配器Adapter度85TargetAdaptee。8789為一個接口提供缺省實現(xiàn)。有了它,就不用直接去實現(xiàn)接口,而是采用集成這個缺省適配對象,從而91 9698102104 106107varclientObject=108 string1:109 string2:110 string3:111112functioninterfaceMethod(str1,str2,str3) 114115116functionclientToInterfaceAdapter(o)117 interfaceMethod(o.string1,o.string2,118119122123125在某些情況下,從客戶一方對代碼進行修改是不可能的。有些程序員因此索性避免創(chuàng)建API。如果現(xiàn)有接口發(fā)生了改變,那么客戶代碼也必須進行相應的修改后才能使用這個新接口,否則整個應用系統(tǒng)就 126128130//Prototype$function$()varelements=for(vari=0;i<arguments.length;i++)varelement= element if(typeofelement=== element if(arguments.length===1)return return146//YUIgetYAHOO.util.Dom.get=function(el) if(YAHOO.lang.isString(el)) if(YAHOO.lang.isArray(el))varc=for(vari=0,len=el.length;i<len;++i) c[c.length]= return if(el)return return164//functionPrototypeToYUIAdapter()return169functionfunctionYUIToPrototypeAdapter(el)returnreturn$.apply(window,elinstanceofArray?el:172$=//180181 <!DOCTYPE<title>MailAPI<metacharset="utf-bodyfont:62.5%georgia,times,#docmargin:0width:font-size:<div ApplicationInterface</h1><li><aclass="thread"id="msg-1"href="#">loadmessageSister<li><aclass="thread"id="msg-2"href="#">loadmessageLindsey<li><aclass="thread"id="msg-3"href="#">loadmessageMargaret<divid="message-212<scriptsrc="Library.js"></<<////applicationvarvarDED=DED.utilDED.util=substitute:substitute:function(s,o)returnreturns.replace(/\{([^\{\}]*)\}/g,function(a,b)varvarr=typeofr?typeofr?r:typeofrasyncRequest:(asyncRequest:(function()functionhandleReadyState(o,callback)o.onreadystatechangeo.onreadystatechangefunction()if(oif(o&&o.readyState4)if((o.statusif((o.status>=200&&o.statusif(callback){}}}}300)||o.status304)newnewvargetXHRfunction()var;tryhttphttpnewgetXHRfunction()}}catch(ex)

varmsxmlvarmsxml=

for(vari=0,len=msxml.length;i<len;i++) try252 http=new253 getXHR=function()

new256 getXHR.str=}}catch(ex)262

returnreturnfunction(method,url,callback,postData)varhttp= http.open(method,url, handleReadyState(http, http.send(postData||return //dedMailapplicationvardedMail=(function()functionrequest(id,type,callback) 'mail-api.php?ajax=true&id='+id++function(o) return getMail:function(id,callback) request(id,'all', sendMail:function(body,recipient)//Sendmailwithbodytextto d save:function(id)//Saveadraftcopywith ID. move:function(id,destination)//Move tothe ddestination archive:function(id)//Archive.Thiscanbeabasicfacademethodthat //themovemethod,hard-codingthe302 trash:function(id)//Thiscanalsobeafacademethodwhichmovesthemessage//thetrash306 reportSpam:function(id)//Movemessagetospamfolderandaddsendertothe309 310 formatMessage:function(e) vare=e|| if(e.preventDefault)313 314 }else315 e.returnValue=316 varvar =e.target||varvarid= 319 dedMail.getMail(id,function(msgObject)

varresp=

+msgObject+vardetails='<p><strong>From:</strong> details+='<strong>Sent:</strong> details+= details+= $('message-pane').innerHTML=DED.util.substitute(details, //Setupmailvarthreads= ,varthreads= ,for(vari=0,len=threads.length;i<len;i++) addEvent(threads[i],'click', </fooMail.getMail(function(text) $('message-oane').innerHTML= ardedMailtoFooMailAdapter=edMailtoFooMailAdapter.getMail=function(id,callback) resp=+resp resp=+respvardetails='<p><strong>From:</strong> details+='<strong>Sent:</strong> callback(DED.util.substitute(details, //OthermethodsneededtoadapterdedMailtothefooMail364//AssigntheadaptertothefooMail365fooMail=dedMailtoFooMailAdapter;368369 372374375379適配器之381可能有些工程師不想使用適配器,其原因主要在于他們實際上需要徹底重寫代碼。有人認為適配器是API用。382////varvarAjaxLogger=sendLog:sendLog:function()varvardataurl:url:data:data:urlEncode:urlEncode:function(arg)returnreturn398 400402varAjaxLoggerAdapter=403 log:function(arg)404 405 406408/*AdjusttheLoggerFactory*/410varLoggerFactory=411 getLogger:function() //justgottachangewhat'sreturned return414 416419420422 427430兩個模式有一個很大的不同:一般適配器適配過后是需要改變接口的,如果不改接口就沒有必要適配 模 來調用Adaptee,這樣436438在適配器實現(xiàn)的時候,通常需要得到被適配的對象。如果被適配的是一個接口,那么就可以結合一些440443//http:/ 445function () //function () this.request=function(zipStart,zipEnd,weight) // return451 452function ()454//function () this.login=function(credentials){/*...*/ this.setStart=function(start){/*...*/ this.setDestination=function(destination){/*...*/ this.calculate=function(weight){return"$39.50";460function Adapter(credentials)var =function Adapter(credentials)var =new returnreturnrequest:request:function(zipStart,zipEnd,weight) returnreturn 472 473 474

//logvarlog=(function(){varlog="";return{ add:function(msg){log+=msg

"\n";

show:function(){alert(log);log

"";486function{varvar =new varcredentials={token:"30a8-new varadapternew //original//original objectandinterfacevarvarcost= .request("78701","10010","2//new objectwithadapted//new objectwithadaptedinterface498 cost=adapter.request("78701","10010","2499 log.add("Newcost:"+cost);501 502503505506507<!DOCTYPE<htmllang="en-<metacharset="utf-9*****定義*定義***本質*本質**離抽象**的* 21 24 假設有一個名為getBeerById的API信息。那個被電擊addEvent(element,'click',functiongetBeearById(e)varid= asyncRequest('GET','beer.uri?id='+id,function(resp)//callback console.log('RequestedBeer: }

+////作為一個優(yōu)良的 functiongetBeearById(id,callback)//makerequestforbeerbyID,thenreturnthebeer asyncRequest('GET','beer.uri?id='+id,function(resp)//callback }addEvent(element,'click',functiongetBeerByIdBridge(e) getBeerById(this.id,function(beer) console.log('RequestedBeer: }55

+ PublicPublicvarsecret

n()this.privilegedGetter=function()return69 70aro=newvardata=o.privilegedGetter();varClass1=function(a,b,c)this.a=this.bthis.b=this.cthis.c=function(d)function(d)varClass2this.dthis.d=function(a,function(a,b,c,d)varBridgeClassnewClass1(a,newClass1(a,b,this.onenewnewthis.two8688 96////添 varasyncRequest=(function()functionhandleReadyState(o,callback) o.onreadystatechange=function()if(o&&o.readyState===4)if((o.status>=200&&o.status<300)||o.status===304)if(callback) callback.call(o,o.responseText, vargetXHR=function()vartryhttpnewhttpfunction()function()getXHRnewnew}}catch(e)varvarmsxml= 123 for(vari=0,len=msxml.length;i<len;i++)try http=new getXHR=function()

new getXHR.str= }catch(e) return138 returnfunction(method,url,callback,postVars)varhttp= handleReadyState(http, http.open(method,url, http.send(postVars||return Ftotype.method=function(name,fn)totype[name]=return153if(!Atotype.forEach) Array.method('forEach',function(fn,thisObj)varscope=thisObj||fn.call(scope,fn.call(scope,this[i],i,}}163ifif(!Atotype.filter)Array.method('filter',Array.method('filter',function(fn,thisObj)}}}}176 177

for(varfor(vari0,lenthis.length;i<len;i++)varscope=thisObjvarscope=thisObj||vara=for(vari0,lenthis.length;i<len;i++)if(!fn.call(scope,this[i],i,this))return//functionisBigEnough(element,index,array)return(element>=182varfiltered=[12,5,8,130,//12,130,window.DED=window.DED||DED.util=DED.util||DED.util.Observer=function()this.fns=192DED.util.Ototype= subscribe:function(fn)196 unsubscribe:function(fn)this.fns=this.fns.filter(function(el)if(el!==fn)return //Core//Corepropertiesthatsetupafrontendqueueingthis.retryCountthis.currentRetry=this.pausedthis.timeoutthis.conn=fire:function(o)this.fns.forEach(this.fns.forEach(function(el)}}DED.QueueDED.Queuefunction()////Queuedthis.queuethis.queue=////ObservableObjectsthatcannotifytheclientof////momentsoneachDED.Queuenewnewpletenewthis.onFailurenewthis.onFailurethis.onFlushnew this.timer=236DED.Queue.method('flush',function()if(!this.queue.length) if(this.paused)this.paused= varthat=varabort=function() if(that.currentRetry===that.retryCount) that.currentRetry= }else this.timer=window.setTimeout(abort,varcallback=function(o) that.currentRetry= if(that.queue.length===0) //

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論