设计模式案例(一)

上传人:a**** 文档编号:241548359 上传时间:2024-07-03 格式:PPT 页数:252 大小:1.75MB
返回 下载 相关 举报
设计模式案例(一)_第1页
第1页 / 共252页
设计模式案例(一)_第2页
第2页 / 共252页
设计模式案例(一)_第3页
第3页 / 共252页
点击查看更多>>
资源描述
DesignPatterns,ArchitecturalPatternsPascalMolliUniversityHenriPoincarPascal.Molliloria.fr1BibliographynASystemofPatternBushmannetAllnDesignPatternsGammaetAllnConcurrentProgramminginJavaD.Lea.nDistributedObjectsOrfalietAllnApplyingUMLandPatternsLarman2PatternsnPatternshelpyoubuildonthecollectiveexperienceofskilledsoftwareengineers.nTheycaptureexisting,wellprovenexperienceinsoftwaredevelopmentandhelptopromotegooddesignpracticenEverypatterndealswithaspecific,recurringprobleminthedesignorimplementationofasoftwaresystemnPatternscanbeusedtoconstructsoftwarearchitectureswithspecificproperties3BecomingaChessMasternFirstlearnrulesandphysicalrequirementse.g.,namesofpieces,legalmovements,chessboardgeometryandorientation,etc.nThenlearnprinciplese.g.,relativevalueofcertainpieces,strategicvalueofcentersquares,powerofathreat,etc.nHowever,tobecomeamasterofchess,onemuststudythegamesofothermastersThesegamescontainpatternsthatmustbeunderstood,memorized,andappliedrepeatedlynTherearehundredsofthesepatterns4BecomingaSoftwareDesignerMasternFirstlearntherulese.g.,thealgorithms,datastructuresandlanguagesofsoftwarenThenlearntheprinciplese.g.,structuredprogramming,modularprogramming,objectorientedprogramming,genericprogramming,etc.nHowever,totrulymastersoftwaredesign,onemuststudythedesignsofothermastersThesedesignscontainpatternsmustbeunderstood,memorized,andappliedrepeatedlynTherearehundredsofthesepatterns5SoftwareArchitecturenAsoftwarearchitectureisadescriptionofthesubsystemsandcomponentsofasoftwaresystemandtherelationshipsbetweenthem.nSubsystemsandcomponentsaretypicallyspecifiedindifferentviewstoshowtherelevantfunctionalandnonfunctionalpropertiesofasoftwaresystem.nThesoftwaresystemisanartifact.Itistheresultofthesoftwaredesignactivity.6ComponentnAcomponentisanencapsulatedpartofasoftwaresystem.Acomponenthasaninterface.nComponentsserveasthebuildingblocksforthestructureofasystem.nAtaprogramminglanguagelevel,componentsmayberepresentedasmodules,classes,objectsorasetrelatedfunctions.7SubsystemsnAsubsystemisasetofcollaboratingcomponentsperformingagiventask.Asubsystemisconsideredaseparateentitywithinasoftwarearchitecture.nItperformsitsdesignatedtaskbyinteractingwithothersubsystemsandcomponents8ArchitecturalPatternsnAnarchitecturalPatternexpressafundamentalstructuralorganizationschemaforsoftwaresystems.Itprovidesasetofpredefinedsubsystems,theirresponsibilities,andincludesrulesandguidelinesfororganizingtherelationshipsbetweenthem.9DesignpatternsnAdesignpatternprovidesaschemeforrefiningthesubsystemsorcomponentsofasoftwaresystem,ortherelationshipsbetweenthem.Itdescribesacommonlyrecurringstructureofcommunicatingcomponentsthatsolvesageneraldesignproblemwithinaparticularcontext.10IdiomsnAnIdiomisalowlevelpatternspecifictoaprogramminglanguage.Anidiomdescribeshowtoimplementparticularaspectsofcomponentsortherelationshipsbetweenthemusingthefeaturesofthegivenlanguage.11FrameworknAframeworkisapartiallycompletesoftware(sub)systemthatisintendedtobeinstantiated.Itdefinesthearchitectureforafamilyof(sub)systemsandprovidesthebasicbuildingblockstocreatethem.Italsodefinestheplaceswhereadaptationsforspecificfunctionalityshouldbemade.12FirstExamplenADiceGamenAPlayerrolls10 x2dicesnIfresult=7,score=score+10pointsnAttheend,scoreoftheplayerisregistredinthehighscoretable.13menuviewHighscoreStartturn=0RollDiceturn+UpdatehighscoreTurnlessbenefits,tomuchlayercomplexityandoverhead25ApplyingLayerArchitecturePlayViewHighScoreFichierouBDDUICorePersistence26PackagedecompositionUICorePersistUtil27LayercorenContainbusinesslogicclassesnAdaptanalysisclassesforimplementationnUseofsingletonIdiom28Singleton(Idiom)nEnsureaclassonlyhasoneinstance,andprovideaglobalpointofaccesstoit.29SingletonStructure30CoreLayer:1erdiagrammeDesignAnalyse31PackagedecompositionUICorePersistUtil32ObservernOnetomanydependencybetweenobjects:changeofoneobjectwillautomaticallynotifyobservers33Observer:ApplicabilitynAchangetooneobjectrequireschanginganunknownsetofothersnObjectshouldbeabletonotifyothersthatmaynotbeknownatthebeginning34Observer:Structure35Observer:ConsequencesnAbstractcouplingbetweensubjectandobservernSupportforbroadcastcommunicationnHardtomaintain36ApplyingObserverPattern37ObserverView38Viewsaregraphicalobjects39SettingupObserver40Observer:ChangePropagation:Die:Randomizer:DieView1:getValue()2:setValue(int)3:notifyObservers()4:update(Observable,Object)5:getState()3:JLabel6:setText(3)41Architectureencouche.UICoreDecouplingclassesandinterfaces42PackagedecompositionUICorePersistUtil43PatternFactoryMethodnIntentDefineaninterfaceforcreatinganobject,butletsubclassesdecidewhichclasstoinstantiateletaclassdeferinstantiationtosubclassesAlsoknownasVirtualConstructor44FactoryMethodnApplicability:Usewhenaclasscannotanticipatetheclassofobjectsitmustcreateaclasswantsitssubclassestospecifytheobjectsitcreatesclassesdelegateresponsibilitytooneofseveralhelpersubclasses,andyouwanttolocalizetheknowledgeofwhichhelpersubclasstodelegate.45Structure46FactorymethodnConsequencesProvidehooksforsubclassesconnectsparallelclasshierarchiesnKnownusesMacApp,ET+ClassViewinsmalltalk80MVC(controllercreation)OrbixORBforgeneratingPROXYobject47LayerPersistnClassestechniquesdepersistancesnAssurerlindpendanceCore/PersistpouvoirchangerdepersistentenginenParexemple:PersistanceparSrialisationPersistanceviaunebasededonnesrelationnelle(JDBC).48ApplyingFactoryProduitabstraitFabriqueabstraiteProduitconcretFabriqueconcrte49ApplyingFactory50Summaryn1Architecturalpattern:Layern2DesignPatterns:Observer,Factoryn1Idiom:SingletonnPb:Combiningpatterntocombinetheirforces5152BankexamplenAbasicbanksystem:1bank,nAccount.Eachaccountbelongto1client.Eachaccountiscreditedbyanamountamoney.nBankfunctionsWithdrawalonaaccount,Creditanaccount,Transfermoneyfromoneaccounttoanother53Naivesolution54NaiveSolution55ApplyingCommandPatternnEncapsulatearequestasanobject,therebylettingyouparameterizeclientswithdifferentrequests,queueorlogrequests,andsupportundoableoperations.56CommandExample57CommandExample58CommandStructure59CommandStructure60CommandConsequencesnCommanddecouplestheobjectthatinvokestheoperationfromtheonethatknowshowtoperformit.nCommandsarefirstclassobjects.Theycanbemanipulatedandextendedlikeanyotherobject.nItseasytoaddnewCommands,becauseyoudonthavetochangeexistingclasses.61ApplyingCommandPattern62ApplyingCommandPattern63CompositePatternnComposeobjectsintotreestructurestorepresentpartwholehierarchies.Compositeletsclientstreatindividualobjectsandcompositionsofobjectsuniformly.64CompositeExample65CompositeExample66CompositeStructure67ApplyingCompositeonCommand68ApplyingComposite6970ApplyingSingleton71AndSoonnStoringstate:MementoPatternnObservingAccount:ObserverPatternnVisitingallobjectgraph:VisitorPatternnRemoteaccess:Proxypatternn72ProxyPatternnProvideasurrogateorplaceholderforanotherobjecttocontrolaccesstoit.73ProxyExample74ProxyStructure75Proxybenefitsnremoteproxycanhidethefactthatanobjectresidesinadifferentaddressspace.nAvirtualproxycanperformoptimizationssuchascreatinganobjectondemand.nBothprotectionproxiesandsmartreferencesallowadditionalhousekeepingtaskswhenanobjectisaccessed.76FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al77AdapterPatternnConverttheinterfaceofaclassintoanotherinterfaceclientsexpect.Adapterletsclassesworktogetherthatcouldntotherwisebecauseofincompatibleinterfaces.78AdapterExample79AdapterStructure80VisitorPatternnRepresentanoperationtobeperformedontheelementsofanobjectstructure.Visitorletsyoudefineanewoperationwithoutchangingtheclassesoftheelementsonwhichitoperates.81Visitorexample82Visitorexample83Visitorapplicabilitynmanydistinctandunrelatedoperationsneedtobeperformedonobjectsinanobjectstructure,andyouwanttoavoidpollutingtheirclasseswiththeseoperations84VisitorStructure85VisitorStructure86VisitorConsequencesnVisitor makes adding new operations easynA visitor gathers related operations and separates unrelated onesnAdding new Concrete Element classes is hardnVisiting across class hierarchiesnAccumulating state.nBreaking encapsulation87ChainofresponsabilitynAvoidcouplingthesenderofarequesttoitsreceiverbygivingmorethanoneobjectachancetohandletherequest.Chainthereceivingobjectsandpasstherequestalongthechainuntilanobjecthandlesit.8889ChainofResponsability90Chainofresponsability91ParticipantsnHandler(HelpHandler)definesaninterfaceforhandlingrequests.(optional)implementsthesuccessorlink.nConcreteHandler(PrintButton,PrintDialog)handlesrequestsitisresponsiblefor.canaccessitssuccessor.iftheConcreteHandlercanhandletherequest,itdoesso;otherwiseitforwardstherequesttoitssuccessor.nClientinitiatestherequesttoaConcreteHandlerobjectonthechain.92ExamplenAwt1.0FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al93StrategynDefineafamilyofalgorithms,encapsulateeachone,andmaketheminterchangeable.Strategyletsthealgorithmvaryindependentlyfromclientsthatuseit.94Strategy95Strategy96ParticipantsnStrategy(Compositor)declaresaninterfacecommontoallsupportedalgorithms.ContextusesthisinterfacetocallthealgorithmdefinedbyaConcreteStrategy.nConcreteStrategy(SimpleCompositor,TeXCompositor,ArrayCompositor)implementsthealgorithmusingtheStrategyinterface.nContext(Composition)isconfiguredwithaConcreteStrategyobject.maintainsareferencetoaStrategyobject.maydefineaninterfacethatletsStrategyaccessitsdata.97StrategyFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al98StatenAllowanobjecttoalteritsbehaviorwhenitsinternalstatechanges.Theobjectwillappeartochangeitsclass.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al99ExempleFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al100StructureFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al101Consequences1.It localizes state-specific behavior and partitions behavior for different states2.It makes state transitions explicit3.State objects can be sharedFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al102DecoratornAttachadditionalresponsibilitiestoanobjectdynamically.Decoratorsprovideaflexiblealternativetosubclassingforextendingfunctionality.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al103ExampleFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al104ExampleFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al105ExampleFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al106StructureFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al107Applicabilityntoaddresponsibilitiestoindividualobjectsdynamicallyandtransparently,thatis,withoutaffectingotherobjects.nforresponsibilitiesthatcanbewithdrawnnwhenextensionbysubclassingisimpracticalFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al108Consequences1.More flexibility than static inheritance2.Avoids feature-laden classes high up in the hierarchy3.A decorator and its component arent identical4.Lots of little objectsFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al109FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al110BridgenDecoupleanabstractionfromitsimplementationsothatthetwocanvaryindependently.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al111BridgeFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al112BridgeFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al113BridgeStructureFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al114Bridge1.Decoupling interface and implementation2.Improved extensibility3.Hiding implementation details from clientsFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al115ExampleFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al116FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al117BuildernSeparatetheconstructionofacomplexobjectfromitsrepresentationsothatthesameconstructionprocesscancreatedifferentrepresentations.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al118BuilderFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al119BuilderStructureFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al120BuilderFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al121BuilderConsequences1.It lets you vary a products internal representation2.It isolates code for construction and representation3.It gives you finer control over the construction processFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al122FlyWeightnUsesharingtosupportlargenumbersoffinegrainedobjectsefficiently.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al123FlyWeightFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al124Flyweight:StructureFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al125FlyweightexampleFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al126Flyweight:InstancesFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al127Flyweight:ApplicabilitnEtatintrinsque/extrinsquenLestatsextrinsquespeuventtrecalculsFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al128Flyweight(ilariencompris)FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al129IteratornProvideawaytoaccesstheelementsofanaggregateobjectsequentiallywithoutexposingitsunderlyingrepresentationFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al130IteratorFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al131Iteratorexample:FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al132ExempleFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al133MementonWithoutviolatingencapsulation,captureandexternalizeanobjectsinternalstatesothattheobjectcanberestoredtothisstatelater.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al134MementoStructureFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al135Memento1.Preserving encapsulation boundaries2.It simplifies Originator3.Using mementos might be expensive.4.Defining narrow and wide interfaces5.Hidden costs in caring for mementosFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al136CaseStudyFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al137DesignproblemsqDocument structure.ThechoiceofinternalrepresentationforthedocumentaffectsnearlyeveryaspectofLexisdesign.Allediting,formatting,displaying,andtextualanalysiswillrequiretraversingtherepresentation.Thewayweorganizethisinformationwillimpactthedesignoftherestoftheapplication.qFormatting.HowdoesLexiactuallyarrangetextandgraphicsintolinesandcolumns?Whatobjectsareresponsibleforcarryingoutdifferentformattingpolicies?Howdothesepoliciesinteractwiththedocumentsinternalrepresentation?FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al138DesignproblemsqEmbellishing the user interface.Lexisuserinterfaceincludesscrollbars,borders,anddropshadowsthatembellishtheWYSIWYGdocumentinterface.SuchembellishmentsarelikelytochangeasLexisuserinterfaceevolves.Henceitsimportanttobeabletoaddandremoveembellishmentseasilywithoutaffectingtherestoftheapplication.qSupporting multiple look-and-feel standards.LexishouldadapteasilytodifferentlookandfeelstandardssuchasMotifandPresentationManager(PM)withoutmajormodification.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al139DesignproblemsqEmbellishing the user interface.Lexisuserinterfaceincludesscrollbars,borders,anddropshadowsthatembellishtheWYSIWYGdocumentinterface.SuchembellishmentsarelikelytochangeasLexisuserinterfaceevolves.Henceitsimportanttobeabletoaddandremoveembellishmentseasilywithoutaffectingtherestoftheapplication.qSupporting multiple look-and-feel standards.LexishouldadapteasilytodifferentlookandfeelstandardssuchasMotifandPresentationManager(PM)withoutmajormodification.FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al140DesignproblemsqSpelling checking and hyphenation.HowdoesLexisupportanalyticaloperationssuchascheckingformisspelledwordsanddetermininghyphenationpoints?Howcanweminimizethenumberofclasseswehavetomodifytoaddanewanalyticaloperation?FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al141FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al142FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al143FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al144FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al145FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al146FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al147FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al148FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al149FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al150FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al151FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al152FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al153FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al154FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al155FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al156FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al157Summary(C.Alexander)nItispossibletomakebuildingbystringingtogetherpatterns,inaratherlooseway.Abuildingmadelikethis,isanassemblyofpatterns.Itisnotdense.Itisnotprofound.Butitisalsopossibletoputpatternstogetherinsuchwaythatmanypatternsoverlapinthesamephysicalspace:thebuildingisverydense;ithasmanymeaningscapturedinasmallspace;andthroughthisdensity,itbecomesprofound.158ArchitecturalPatternsnFromMUDtoStructureLayers,PipeandFilters,BlackboardnDistributedSystemsBroker,PipeandFilters,MicrokernelnInteractiveSystemsMVC,PACnAdaptableSystemsMicrokernel,Reflection159Layernhelpstostructureapplicationthatcanbedecomposedintogroupsofsubtasksinwhicheachgroupofsubtasksisataparticularlevelofabstraction.160Layer:examples161Layer:Structure162Layer:Structure163Layerandcomponents164LayerandFacadeDP165LayerandFacadeDP166Layers:VariantsnRelaxedLayeredSystem:Alayerjcanuseserviceofj1,j2AlayercanbepartiallyopaqueSomeservicetolayerj+1,otherstoallupperservicesnLayeringthroughinheritance:LowerlayersareimplementedasbaseclassesHigherlevelcanoverridelowerlevel167Layers:KnownUsesnVirtualmachines:JVMandbinarycodeformatnAPI:LayerthatencapsulateslowerlayersnInformationSystemPresentation,Applicationlogic,DomainLayer,DatabasenWindowsNT(relaxedfor:kernelandIOandhardware)Systemservices,Resourcemanagement(Objectmanager,securitymonitor,processmanager,I/Omanager,VMmanager,LPC),Kernel(exceptionhandling,interrupt,multiprosynchro,threads),HAL(HardwareAbstractionLevel)Hardware168Layers:benefitsnReuseoflayersnSupportforstandardization(POSIX)nDependenciesarekeptlocalnExchangeabilities:ReplacementofoldimplementationwithAdapterPatternDynamicexchangewithBridgePattern169Layers:LiabilitiesnCascadesofchangingbehaviornLowerefficiencynUnnecessarywork:functionsofalayercalledmanytimesforoneservicenDifficultyofestablishingcorrectgranularityoflayers:Tofewlayerlessbenefits,tomuchlayercomplexityandoverhead170PipesandFiltersnProvidesastructureforsystemsthatprocessastreamofData.Eachprocessingstepisencapsulatedinafiltercomponent.Dataispassedthroughpipesbetweenadjacentfilters.nRecombiningfiltersallowstobuildfamiliesofrelatedsystems.171PipesandFilters:Example172PipesandFilters:Structure173PipesandFilters174PipesandFilters:pushpipeline175PipesandFilters:pullpipeline176PipesandFilters:push-pullpipeline177PipesandFilters:ThreadedFilters178PipesandFilters:KnownUsesnUnixnCMSPipelines(extensionIBMmainframes)nLASSPTools(NumericalAnalysis)Graphicalinputdevices(knobsorsliders)FiltersfornumericalanalysisanddataextractionDatasinkstoproduceanimationfromnumericaldatastreamsnKhoros:ImagerecognitionnWEB!Servlet!179PipesandFiltersbenefitsnNointermediatefilenecessary(butpossible)nFlexibilitybyfilterexchangenFlexibilitybyrecombinationnReuseoffiltercomponentsnRapidprototypingofpipelinenEfficiencybyparallelprocessing180PipesandFiltersLiabilitiesnSharingstateinformationisexpensiveorinflexiblenEfficiencygainbyparallelprocessingisoftenanillusionCostofdatatransfer,filtersthatconsumealldatabeforeoneoutput,contextswitchononecomputer,synchronizationoffiltersviapipesnDatatransformationoverheadnErrorHandling181SunDeveloppersFromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al182FromSystemofPatternsBuschmann&AllandDesignPatternGamma&Al183BlackboardThe Blackboard architectural pattern is useful for problems for which no deterministic solution strategies are known.Several specialized subsystems assemble their knowledge to b
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 商业管理 > 商业计划


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!