版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
<!doctype<html<metacharset="UTF-<title>8**********但是抽象工厂着重的就是为一个产品簇选择实现,定义在抽象工厂里面**1.*******3.*2.*****44**48var Factory=function()Ftotype= *示例方法,创建抽象产品A *@return{[type]}抽象产品A createProductA:function() //创建抽象产品 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******** *要实现同样的构建过程可以创建不同的表现,那么一个自然的思路就是先把构建过程独立出来,在模式中把它称为指导者,由它来指导装配过程,但步的对象,在模式中称这些实现对象为。*是可以被切换的**主要功能是构建复杂的产品,而且是细化的,分步骤的构建产品,也就是模式中在一步一步解决构造复杂对象的问题。更为重要的是,这个构建的过程是统一的,固定不变的,变化的部分放到*模式的重心在于分离构建算法和具体的构造实现,从而使得构建*模式的时候,可以让客户端创模式的时候,可以让客户端创造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接口的实现中,每个部件构建的方法里面,除了部件装配再进一步,如果在实现Builder的时候,只有创建对象的功能,而没有组装的功能。那么这个时候的Builder实现跟抽象工厂的实现是类似的。类似于具体的工厂,而且Builder接口里面定义的创建各个部件的方法也是有关联 才会调 1641643.165171171174了,但是指导者是不负责具体的部件创建和组装的,因此客户端是从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来实现。有抽象工厂模式负责部件对象创建,Builder 实现。 模式Director用来定义整体的构建算法,把算法中某些涉及到具体部件对象的创建和装配功能,委托给具体的Builder来实现。3003011).目的: 3022)。实现 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法根据所要求的自行switch句创建一个自行车的实例。各种型号的自行车实例可以互换使用,因为它们都实现了Bicycle接口.接口在工厂模式中起着很重要的作用。如果不对对象进行某种类型检查以确保其实现了必须的方法,/*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如果需要像前面自行车的例子一样,创建一些用不同方式实现同一接口的对象,那么可以使用一个工*省设置 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如果根本不可能另外换用一个类,或者不需要在运行期间在一系列可互换的类中进行选择,那就不应可以一眼就看到调用的是什么构造函数,而不必去查看某个工厂方法以便知道实例化的是什么类。工厂 521523524526*527528简单工厂使用来选择实现的,可以选择任意接口的实现。一个简单工厂可以有多个用于选择并创建对529抽象工厂模式使用来选择产品簇的实现的,也就是说一般抽象工厂里面有多个用于选择并创建对象的 532*533534工厂方法的本质也使用来选择实现的,跟简单工厂的区别在于工厂方法是把选择具体实现的功能延迟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适配器的实现方式其实是依靠对象组合的方式。通过给适配器对象组合被适配的对象,然后当客户端Target的时候,适配器会把相应的功能委托给被适配对象去完成。6466target--Adapter--676970具体实现里面调用Adaptee。也就是说适配器通常是一个Target类型,而不是Adaptee类型。74 83适配器Adapter度85TargetAdaptee。8789为一个接口提供缺省实现。有了它,就不用直接去实现接口,而是采用集成这个缺省适配对象,从而91 9698102104 106107varclientObject=108 string1:109 string2:110 string3:111112functioninterfaceMethod(str1,str2,str3) 114115116functionclientToInterfaceAdapter(o)117 interfaceMethod(o.string1,o.string2,118119122123125在某些情况下,从客户一方对代码进行修改是不可能的。有些程序员因此索性避免创建API。如果现有接口发生了改变,那么客户代码也必须进行相应的修改后才能使用这个新接口,否则整个应用系统就 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在适配器实现的时候,通常需要得到被适配的对象。如果被适配的是一个接口,那么就可以结合一些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: }
+////作为一个优良的 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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- GB/T 44748.1-2024筛分试验第1部分:使用金属丝编织网和金属穿孔板试验筛的方法
- 医院合同模板
- 农村民房租赁合同
- 2024年度工程公司市场拓展合作协议2篇
- 玫瑰花加工生产销售合同(2024版)
- 二零二四年度医疗信息化系统集成合同3篇
- 烟草法律进校园课件
- 公司与员工签订车辆使用协议
- 美发店转让合同范本
- 苏教版詹天佑教育课件
- 建筑施工安全生产标准化项目自评表
- zxun ims网元号码分析详细说明
- 大学生个人职业生涯规划书【6篇】
- 工程机械设计-陈海虹课件第2章-单斗液压挖掘机
- GB/T 3733.2-1983卡套式端直通接头体
- GB/T 15048-1994硬质泡沫塑料压缩蠕变试验方法
- 廉租住房分配实施方案
- 食品添加剂E编码中英文对照表
- 篮球场改造工程施工组织设计方案
- 小学生飞机知识科普课件
- 利乐TBA9培训演示文稿课件
评论
0/150
提交评论