《23个设计模式C#代码.docx》由会员分享,可在线阅读,更多相关《23个设计模式C#代码.docx(14页珍藏版)》请在课桌文档上搜索。
1、/AbstractFactory/Intent:Provideaninterfaceforcreatingfamiliesofrelatedor/dependentobjectswithoutspecifyingtheirconcreteclasses”./Forfurtherinformation,readDesignPatterns,p87,Gammaetal.,/Addison-Wesley,ISBN:0-201-63361-2*Notes:* Whentheconstructionneededinvolvesmanyobjects,possibleorganised* inmulti-
2、facetedarrangements,theentireconstructioncanbedelegated* toanabstractfactory.Thisexposesstandardisedcreationfunctionality* whichcanbecustomisedinconcreteimplementationtosuityourspecific* needs,andavoidembeddingthisinformationinhigherlevelcode-it* justneedstoknowhowtocalltheabstractfactory.* Inthissa
3、mple,wehaveaframeworkwiththreeabstractoperatingclasses,* calledDPDocument,DPWorkspaceandDPViewandoneabstractconstruction* class,calledDPFactory.napplication-levelclass,calledDPApplication* isresponsibleforconstruction.* Wehaveaseriesofapp1ication-1eve1operatingclassesderivedfromthis* framework-MyDoc
4、ument,MyWorkspaceandMyView.Fordesignreasonswe* assumewewishtoinstantiatethesefrominsideDPApplication.Asthere* aremultipleobjectsneededandtheycouldbearrangedindifferent* lattices,weuseafactory,MyFactory(inourexample,thereareall* simplesiblings),whichiscalledinsideDPApplication.*/namespaceAbstractFact
5、oryDesignPatternusingSystem;/Theseclassescouldbepartofaframework,/whichwewillcallDP/=abstractclassDPDocumentabstractpublicvoidDump();abstractclassDPWorkspaceabstractpublicvoidDump();DPViewpublicvoidDump();abstractclass(abstractabstractclassabstractabstractabstractDPFactorypublicDPDocumentCreateDocum
6、ent();publicDPViewCreateViewO;publicDPWorkspaceCreateWorkspaceO;abstractclassDPApplication(protectedDPDocumentdoc;protectedDPWorkspaceworkspace;protectedDPViewview;publicvoidConstructObjects(DPFactoryfactory)(/Createobjectsasneededdoc=factory.CreateDocumentO;workspace=factory,CreateWorkspaceO;view=f
7、actory.CreateViewO;publicvoidDumpState()(if(doc!-null)doc.Dump();if(workspace!=null)workspace.Dump();if(view!=null)view.DumpO;)/TheseclassescouldbepartofanapplicationclassMyApplication:DPApplicationMyFactorymyFactory=newMyFaCtory();overridepublicvoidDump()(Console.Write1.ine(,MyApplicationexists);pu
8、blicvoidCreateFamilyO(MyFactorymyFactory=newMyFactoryO;ConstructObjects(myFactory);)classMyDocument:DPDocumentpublicMyDocumentO(Console.Write1.ine(,inMyDocumentconstructor);overridepublicvoidDump()(Console.Write1.ine(,MyDocumentexists);)classMyWorkspace:DPWorkspaceConsole.Write1.ine(zzMyWorkspaceexi
9、sts);classMyView:DPViewoverridepublicvoidDump()Console.Write1.ine(,MyViewexists);classMyFactory:DPFactory(overridepublicDPDocumentCreateDocument()(returnnewMyDoCUment();overridepublicDPWorkspaceCreateWorkspace()(returnnewMyWorkspace();)overridepublicDPViewCreateViewOreturnnewMyViewO;IIIIIISummarydes
10、criptionforClient.IllpublicclassClient(publicstaticintMain(stringargs)(MyApplicationmyApplication=newMyApplicationO;myApplication.CreateFamilyO;myApplication.DumpStateO;returnO;/Adapter/Intent:Converttheinterfaceofaclassintoanotherinterface/clientsexpect.Adapterletsclassesworktogetherthatcouldn,t/ot
11、herwisebecauseofincompatibleinterfaces./Forfurtherinformation,readDesignPatterns”,pl39,Gammaetal.,/Addison-Wesley,ISBN:0-201-63361-2*Notes:* Adaptersareoftenusedwhenclientcodeiswrittentoexpectclasses* fromoneframework,anditmeanttoworkwithclassesfromatotally* differentframework.Assumeyoucannotchanget
12、hecodeofeitherframework.* thesolutionisforyoutowriteanadapter,whichappearslikea*nativeclasstoeachframework.* Therearetwodifferenttypesofadapters-classadapterandobject* adapter.Classadaptersarebasedonmultipleinheritance-specifically* theinterfaceofthetargetclassandtheimplementationoftheadaptee.* Unfo
13、rtunatelyC#supportsmultipleinheritanceforinterfacesbutnot* forclasses.Objectadaptersderivefromthetarget(singleinheritance)* andmaintainaprivateinstanceoftheadoptee.* Thesamplecodehereshowsanobjectadapter.Wehaveaclasscalled* FrameworkYAdapteewhichwewishtouse,yetthe(bulkof)theclientcode* (inGenericCli
14、entCode)iswrittentoexpectaclasscalledFrameworkXTarget.* TosolvetheprobelmwecreateanAdapterclass,whichitaFrameworkXTarget* totheclient,andcallsFrameworkYAdaptee.*/namespaceAdaPteJDeSignPaXternusingSystem;classFrameworkXTargetvirtualpublicvoidSomeRequest(intx)(/normalimplementationofSomeRequestgoesher
15、eclassFrameworkYAdaptee(publicvoidQuiteADifferentRequest(stringstr)(Console.Write1.ine(zzQuiteADifferentRequest=0,str);)classOurAdapter:FrameworkXTarget(privateFrameworkYAdapteeadaptee=newFrameworkYAclaptee();overridepublicvoidSomeRequest(inta)(stringb;b=a.ToStringO;adaptee.QuiteADifferentRequest(b)
16、;IIIIIISummarydescriptionforClient.IllpublicclassClientvoidGenericClientCode(FrameworkXTargetx)/Weassumethisfunctioncontainsclient-sidecodethatonly/knowsaboutFrameworkXTarget.x.SomeRequest(4);/othercallstoFrameworkXgohere/.)publicstaticintMain(stringargs)(Clientc=newClient();FrameworkXTargetx=newOur
17、Aclapter();c.GenericClientCode(x);returnO;/Bridge/Intent:DecoupleanabstractionfromitsimpIemntationsothatthe/twocanvaryindependently./Forfurtherinformation,readzzDesignPatterns”,pl51,Gammaetal.,/Addison-Wesley,ISBN:0-201-63361-2*Notes:* Couplingbetweenclassesandclasslibrariesisamajormaintenance* head
18、ache.Toeasethisproblem,oftentheclienttalkstoan* abstractiondescription,whichinturncallsanimplementation.* Sometimesthesemustevolve-whenonechangestherecanbeaneed* tochangetheother.Thebridgedesignpatternletstheabstraction* anditsimplementationevolveseparately.* So,whatisthedifferencebetweenabridgeanda
19、ninterface?Interfaces* canbeusedwhencreatingbridges-butitshouldbenotedthatbridges* haveadditionalpossibilities.Boththeabstractionandthe* implementationmayevolveovertimeandbetheparentofderivedclasses.* Theoperationsneededintheimplementationcouldbedefinedinan*interfaceiftherearenostandardmethodswhicha
20、reavailableatthe* top-leveloftheimplementation.*/namespaceBridgeDesignPattern(usingSystem;classAbstraction(protectedImplementationimpToUse;publicvoidSetlmplementationdmplementationi)(impToUse=i;)virtualpublicvoidDumpString(stringstr)impToUse.DoStringOp(str);)classDerivedAbstractionOne:Abstraction(ov
21、erridepublicvoidDumpString(stringstr)(str+=.comz,;impToUse.DoStringOp(str);classImplementationpublicvirtualvoidDoStringOp(stringstr)Console.Write1.ine(z,Standardimplementation-printstringasis);Console.Write1.ine(z,string=0”,str);classDerivedImp1ementation_One:Implementation(overridepublicvoidDoStrin
22、gOp(stringstr)Console.Write1.ine(z/DerivedImplementation_One-don,tprintstringz,);)classDeriveclImplementationTwo:Implementation(overridepublicvoidDoStringOp(stringstr)(Console.Write1.ine(,zDeriVedImplementation_Two-printstringtwicez,);Console.Write1.ine(,string=0,str);Console.Write1.ine(z,string=0,s
23、tr);)IIIIIISummarydescriptionforClient.IllpublicclassClientAbstractionSetupMyparticularAbstraction()(/welocalizetothismethodthedecisionwhichabstractionand/whichimplementationtouse.Theseneedtobedecided/somewhereandwedoithere.Alltehrestoftheclient/codecanworkagainsttheabstractionobject.Abstractiona=ne
24、wDerivedAbstraction_One();a.Setimplementation(newDerivedImplementation_TwoO);returna;publicstaticintMain(stringargs)Clientc=newClient();Abstractiona=c.SetupMyParticularAbstraction();/Fromhereonclientcodethinksitistalkingtothe/abstraction,andwillnotneedtobechangedas/derivedabstractionsarechanged./mor
25、eclientcodeusingtheabstractiongoeshere.a.DumpString(z,Clipcodez,);return0;/Builder/Intent:Separatetheconstructionofacomplexobjectfromits/representationsothatthesameconstructionprocesscancreate/differentrepresentations./Forfurtherinformation,read“DesignPatterns”,p97,Gammaetal.,/Addison-Wesley,ISBN:0-
26、201-63361-2*Notes:* BuiIderisanobjectcreationaldesignpatternthatcodifiesthe* constructionprocessoutsideoftheactualstepsthatcarriesout* theconstruction-thusallowingtheconstructionprocessitself* tobereused.*/namespaceBuilder_DesignPattern(usingSystem;/Thesetwoclassescouldbepartofaframework,/whichwewil
27、lcallDP/=classDirectorpublicvoidConstruct(AbstractBuilderabstractBuiIder)(abstractBuiIder.BuildPartAO;if(1=1)/representssomelocaldecisioninsidedirectorabstractBuiIder.BuildPartBO;abstractclass(abstractabstractabstractabstractBuiIder.BuiIdPartCO;AbstractBuilclerpublicvoidBuildPartAO;publicvoidBuildPa
28、rtBO;publicvoidBuildPartCO;/Thesetwoclassescouldbepartofanapplication/=classConcreteBuilder:AbstractBuiIder(overridepublicvoidBuildPartAO/CreatesomeobjecthereknowntoConcreteBuiIderConsole.Write1.ine(zzConcreteBuilder.BuildPartACalIeCr);)overridepublicvoidBuildPartBO(/CreatesomeobjecthereknowntoConcr
29、eteBuilderConsole.Write1.ine(,ConcreteBuiIder.BuildPartBcalled);)overridepublicvoidBuildPartCO/CreatesomeobjecthereknowntoConcreteBuilclerConsole.Write1.ine(,ConcreteBuiIder.BuildPartCcalled7);)IIIIIISummarydescriptionforClient.IllpublicclassClient(publicstaticintMain(stringargs)(ConcreteBuilderConc
30、reteBuilder=newConcreteBuiIder();Directordirector=newDirectorO;director.Construct(concreteBuiIder);returnO;)/ChainOfResponsibility/Intent:,Avoidcouplingthesenderofarequesttoitsreceiverbygiving/morethanoneobjectachancetohandlethereuqest.Chainthereceiving/objectsandpasstherequestalongthechainuntilanob
31、jecthandlesit./Forfurtherinformation,readDesignPatterns”,p223,Gammaetal.,/Addison-Wesley,ISBN:0-201-63361-2*Notes:* Theclientsendsarequestanditwillbeoperatedonbyoneofanumber* ofpotentialreceivers,inachain.Theclientdoesnotknow(anddoes* notneedtoknow)whichreceiverhandlestherequest.Thereceiversare* ina
32、chain,andtherequestispassedfromonetothenext,untilone* receiveractuallyperformstherequest.*/namespaceChainOfResponsibiIity_DesignPattern(usingSystem;abstractclassHandlerprotectedHandlersuccessorHandler;abstractpublicvoidHandleRequest(Requestrequest);publicvoidSetSuccessor(Handlersucessor)(successorHa
33、ndler=sucessor;)classConcreteHandIerl:Handler(overridepublicvoidHandleRequest(Requestrequest)/determineifwecanhandletherequestif(request.RequestType=1)/somecomplexdecisionmaking!(/requesthandlingcodegoeshereConsole.Write1.ine(z,requesthandledinConcreteHandler/);else(/nothandledhere-passontonextinthe
34、chainif(successorHandler!=null)successorHandler.HandleRequest(request);)classConcreteHandler2:HandleroverridepublicvoidHandleRequest(Requestrequest)/determineifwecanhandletherequestif(request.RequestType=2)/somecomplexdecisionmaking!/requesthandlingcodegoeshereConsole.Write1.ine(requesthandledinConC
35、reteHandIer2);)else/nothandledhere-passontonextinthechainif(successorHandler!=null)SuccessorHandler.HandleRequest(request);classConcreteHand1er3:Handler(overridepublicvoidHandleRequest(Requestrequest)/determineifwecanhandletherequestif(request.RequestType=3)/somecomplexdecisionmaking!(/requesthandlingcodegoeshereConsole.Write1.ine(z,requesthandledinConcreteHandler3z);else(/nothandledhere-passontonextinthechainif(successorHandler!=null)successorHandler.HandleRequest(request);)classRequestprivateintiRequestType;privatestringStrRequestParameters;