Design Patterns - SourceMaking
文章推薦指數: 80 %
In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a ... 🤖📘🍻Hooray!After3yearsofwork,we'vefinallyreleasedanewebookondesignpatterns!Checkitout» DesignPatterns Insoftwareengineering,a designpatternisageneralrepeatablesolutiontoacommonlyoccurringprobleminsoftwaredesign.Adesignpatternisn'tafinisheddesignthatcanbetransformeddirectlyintocode.Itisadescriptionortemplateforhowtosolveaproblemthatcanbeusedinmanydifferentsituations. UsesofDesignPatterns Designpatternscanspeedupthedevelopmentprocessbyprovidingtested,provendevelopmentparadigms.Effectivesoftwaredesignrequiresconsideringissuesthatmaynotbecomevisibleuntillaterintheimplementation.Reusingdesignpatternshelpstopreventsubtleissuesthatcancausemajorproblemsandimprovescodereadabilityforcodersandarchitectsfamiliarwiththepatterns. Often,peopleonlyunderstandhowtoapplycertainsoftwaredesigntechniquestocertainproblems.Thesetechniquesaredifficulttoapplytoabroaderrangeofproblems.Designpatternsprovidegeneralsolutions,documentedinaformatthatdoesn'trequirespecificstiedtoaparticularproblem. Inaddition,patternsallowdeveloperstocommunicateusingwell-known,wellunderstoodnamesforsoftwareinteractions.Commondesignpatternscanbeimprovedovertime,makingthemmorerobustthanad-hocdesigns. Creationaldesignpatterns Thesedesignpatternsareallaboutclassinstantiation.Thispatterncanbefurtherdividedintoclass-creationpatternsandobject-creationalpatterns.Whileclass-creationpatternsuseinheritanceeffectivelyintheinstantiationprocess,object-creationpatternsusedelegationeffectivelytogetthejobdone. AbstractFactory Createsaninstanceofseveralfamiliesofclasses Builder Separatesobjectconstructionfromitsrepresentation FactoryMethod Createsaninstanceofseveralderivedclasses ObjectPool Avoidexpensiveacquisitionandreleaseofresourcesbyrecyclingobjectsthatarenolongerinuse Prototype Afullyinitializedinstancetobecopiedorcloned Singleton Aclassofwhichonlyasingleinstancecanexist Structuraldesignpatterns ThesedesignpatternsareallaboutClassandObjectcomposition.Structuralclass-creationpatternsuseinheritancetocomposeinterfaces.Structuralobject-patternsdefinewaystocomposeobjectstoobtainnewfunctionality. Adapter Matchinterfacesofdifferentclasses Bridge Separatesanobject’sinterfacefromitsimplementation Composite Atreestructureofsimpleandcompositeobjects Decorator Addresponsibilitiestoobjectsdynamically Facade Asingleclassthatrepresentsanentiresubsystem Flyweight Afine-grainedinstanceusedforefficientsharing PrivateClassData Restrictsaccessor/mutatoraccess Proxy Anobjectrepresentinganotherobject Behavioraldesignpatterns ThesedesignpatternsareallaboutClass'sobjectscommunication.Behavioralpatternsarethosepatternsthataremostspecificallyconcernedwithcommunicationbetweenobjects. Chainofresponsibility Awayofpassingarequestbetweenachainofobjects Command Encapsulateacommandrequestasanobject Interpreter Awaytoincludelanguageelementsinaprogram Iterator Sequentiallyaccesstheelementsofacollection Mediator Definessimplifiedcommunicationbetweenclasses Memento Captureandrestoreanobject'sinternalstate NullObject Designedtoactasadefaultvalueofanobject Observer Awayofnotifyingchangetoanumberofclasses State Alteranobject'sbehaviorwhenitsstatechanges Strategy Encapsulatesanalgorithminsideaclass Templatemethod Defertheexactstepsofanalgorithmtoasubclass Visitor Definesanewoperationtoaclasswithoutchange Criticism Theconceptofdesignpatternshasbeencriticizedbysomeinthefieldofcomputerscience. Targetsthewrongproblem Theneedforpatternsresultsfromusingcomputerlanguagesortechniqueswithinsufficientabstractionability.Underidealfactoring,aconceptshouldnotbecopied,butmerelyreferenced.Butifsomethingisreferencedinsteadofcopied,thenthereisno"pattern"tolabelandcatalog.PaulGrahamwritesintheessay RevengeoftheNerds. PeterNorvigprovidesasimilarargument.Hedemonstratesthat16outofthe23patternsintheDesignPatternsbook(whichisprimarilyfocusedonC++)aresimplifiedoreliminated(viadirectlanguagesupport)inLisporDylan. Lacksformalfoundations Thestudyofdesignpatternshasbeenexcessivelyadhoc,andsomehavearguedthattheconceptsorelyneedstobeputonamoreformalfooting.At OOPSLA1999,theGangofFourwere(withtheirfullcooperation)subjectedtoashowtrial,inwhichtheywere"charged"withnumerouscrimesagainstcomputerscience.Theywere"convicted"by⅔ofthe"jurors"whoattendedthetrial. Leadstoinefficientsolutions Theideaofadesignpatternisanattempttostandardizewhatarealreadyacceptedbestpractices.Inprinciplethismightappeartobebeneficial,butinpracticeitoftenresultsintheunnecessaryduplicationofcode.Itisalmostalwaysamoreefficientsolutiontouseawell-factoredimplementationratherthana"justbarelygoodenough"designpattern. Doesnotdiffersignificantlyfromotherabstractions Someauthorsallegethatdesignpatternsdon'tdiffersignificantlyfromotherformsofabstraction,andthattheuseofnewterminology(borrowedfromthearchitecturecommunity)todescribeexistingphenomenainthefieldofprogrammingisunnecessary.TheModel-View-Controllerparadigmistoutedasanexampleofa"pattern"whichpredatestheconceptof"designpatterns"byseveralyears.ItisfurtherarguedbysomethattheprimarycontributionoftheDesignPatternscommunity(andtheGangofFourbook)wastheuseofAlexander'spatternlanguageasaformofdocumentation;apracticewhichisoftenignoredintheliterature. Moreinfo,diagramsandexamplesofthedesignpatternsyoucanfindonournewpartnerresourceRefactoring.Guru. SupportourfreewebsiteandowntheeBook! 22designpatternsand8principlesexplainedindepth 406well-structured,easytoread,jargon-freepages 228clearandhelpfulillustrationsanddiagrams Anarchivewithcodeexamplesin4languages Alldevicessupported:EPUB/MOBI/PDFformats Learnmore... Readnext Creationalpatterns DiveIntoDesignPatterns new Hey,checkoutournew ebookondesignpatterns.Thebookcovers22patternsand8designprinciples,allsuppliedwithcodeexamplesandillustrations.Clear,shortandfun! Oh,anditisonsalerightnow. Facebook Twitter Contactus Login PremiumStuff DiveIntoDesignPatterns DiveIntoRefactoring ComputerScienceDistilled DesignPatterns Creationalpatterns AbstractFactoryDesignPattern BuilderDesignPattern FactoryMethodDesignPattern ObjectPoolDesignPattern PrototypeDesignPattern SingletonDesignPattern Structuralpatterns AdapterDesignPattern BridgeDesignPattern CompositeDesignPattern DecoratorDesignPattern FacadeDesignPattern FlyweightDesignPattern PrivateClassData ProxyDesignPattern Behavioralpatterns ChainofResponsibility CommandDesignPattern InterpreterDesignPattern IteratorDesignPattern MediatorDesignPattern MementoDesignPattern NullObjectDesignPattern ObserverDesignPattern StateDesignPattern StrategyDesignPattern TemplateMethodDesignPattern VisitorDesignPattern AntiPatterns SoftwareDevelopmentAntiPatterns TheBlob ContinuousObsolescence LavaFlow AmbiguousViewpoint FunctionalDecomposition Poltergeists BoatAnchor GoldenHammer DeadEnd SpaghettiCode InputKludge WalkingthroughaMinefield Cut-And-PasteProgramming MushroomManagement SoftwareArchitectureAntiPatterns AutogeneratedStovepipe StovepipeEnterprise Jumble StovepipeSystem CoverYourAssets VendorLock-In WolfTicket ArchitectureByImplication WarmBodies DesignByCommittee SwissArmyKnife ReinventTheWheel TheGrandOldDukeofYork ProjectManagementAntiPatterns BlowhardJamboree AnalysisParalysis ViewgraphEngineering DeathByPlanning FearofSuccess Corncob IntellectualViolence IrrationalManagement SmokeandMirrors ProjectMismanagement ThrowItovertheWall FireDrill TheFeud E-mailIsDangerous Refactoring CodeSmells Bloaters LongMethod LargeClass PrimitiveObsession LongParameterList DataClumps Object-OrientationAbusers SwitchStatements TemporaryField RefusedBequest AlternativeClasseswithDifferentInterfaces ChangePreventers DivergentChange ShotgunSurgery ParallelInheritanceHierarchies Dispensables Comments DuplicateCode LazyClass DataClass DeadCode SpeculativeGenerality Couplers FeatureEnvy InappropriateIntimacy MessageChains MiddleMan OtherSmells IncompleteLibraryClass Refactoringtechniques ComposingMethods ExtractMethod InlineMethod ExtractVariable InlineTemp ReplaceTempwithQuery SplitTemporaryVariable RemoveAssignmentstoParameters ReplaceMethodwithMethodObject SubstituteAlgorithm MovingFeaturesbetweenObjects MoveMethod MoveField ExtractClass InlineClass HideDelegate RemoveMiddleMan IntroduceForeignMethod IntroduceLocalExtension OrganizingData SelfEncapsulateField ReplaceDataValuewithObject ChangeValuetoReference ChangeReferencetoValue ReplaceArraywithObject DuplicateObservedData ChangeUnidirectionalAssociationtoBidirectional ChangeBidirectionalAssociationtoUnidirectional ReplaceMagicNumberwithSymbolicConstant EncapsulateField EncapsulateCollection ReplaceTypeCodewithClass ReplaceTypeCodewithSubclasses ReplaceTypeCodewithState/Strategy ReplaceSubclasswithFields SimplifyingConditionalExpressions DecomposeConditional ConsolidateConditionalExpression ConsolidateDuplicateConditionalFragments RemoveControlFlag ReplaceNestedConditionalwithGuardClauses ReplaceConditionalwithPolymorphism IntroduceNullObject IntroduceAssertion SimplifyingMethodCalls RenameMethod AddParameter RemoveParameter SeparateQueryfromModifier ParameterizeMethod ReplaceParameterwithExplicitMethods PreserveWholeObject ReplaceParameterwithMethodCall IntroduceParameterObject RemoveSettingMethod HideMethod ReplaceConstructorwithFactoryMethod ReplaceErrorCodewithException ReplaceExceptionwithTest DealingwithGeneralisation PullUpField PullUpMethod PullUpConstructorBody PushDownMethod PushDownField ExtractSubclass ExtractSuperclass ExtractInterface CollapseHierarchy FormTemplateMethod ReplaceInheritancewithDelegation ReplaceDelegationwithInheritance UML Introduction BasicPrinciplesandBackground IntroductiontotheCaseStudy Models,Views,andDiagrams InformationSystemsandITSystems TheModelsofourCaseStudy HistoryofUML:MethodsandNotations RequirementSpecification UML2.0 ModelingBusinessSystems BusinessProcessesandBusinessSystems OneModel—TwoViews ExternalView TheElementsofaView UseCaseDiagrams ConstructingUseCaseDiagrams ActivityDiagrams ConstructingActivityDiagrams SequenceDiagrams ConstructingSequenceDiagrams High-LevelSequenceDiagrams SequenceDiagramsforScenariosofBusinessUseCases InternalView PackageDiagram ConstructingPackageDiagrams ClassDiagram ConstructingClassDiagrams ActivityDiagram ModelingITSystems ExternalView TheUserViewor"Idon'tcarehowitworks,aslongasitworks." TheElementsofaView UseCaseDiagram QueryEventsandMutationEvents UseCaseSequenceDiagram ConstructingtheExternalView StructuralView ObjectsandClasses Generalization,Specialization,andInheritance StaticandDynamicBusinessRules ElementsoftheView ClassDiagram ConstructingClassDiagrams TheBehavioralView TheLifeofanObject TheElementsoftheView StatechartDiagram ConstructingStatechartDiagrams InteractionView SeeingWhatHappensInsidetheITSystem ElementsoftheView CommunicationDiagram SequenceDiagram ConstructingCommunicationDiagrams ConstructingSequenceDiagrams ModelingforSystemIntegration TerminologyofSystemIntegration MessagesinUML OneModel—TwoViews ProcessView TheBusinessSystemModelasFoundation ElementsoftheView ActivityDiagrams SequenceDiagram ConstructingDiagramsintheProcessView TheStaticView ElementsoftheView ClassDiagram ConstructingClassDiagrams TransformingDatafromtheITSystemtotheMessage"passengerlist" TransformationofUMLMessagesintoVariousStandardFormats Login Feedback
延伸文章資訊
- 1什麼是設計模式(Design Pattern)? 設計模式系列文(上)
模式(Pattern),以一句話來解釋:. 描述在特定情境(Context)下,解決設計問題(Problem) 的最佳實踐。 而模式中所提出的 ...
- 2這可能是你第一個接觸到的Design Pattern - 叡揚資訊
這次要跟大家介紹的是Composite Pattern,這是GoF(Gang of Four)經典的23種設計模式之一,GoF把設計模式分為三種: Creational Patterns; St...
- 3設計模式(電腦) - 維基百科,自由的百科全書
在軟體工程中,設計模式(design pattern)是對軟體設計中普遍存在(反覆出現)的各種問題,所提出的解決方案。這個術語是由埃里希·伽瑪(Erich Gamma)等人在1990年代 ...
- 4為什麼要學Design Pattern
一般軟體圈講的設計模式是指GoF 的23個design pattern ,而GoF 的23個設計模式全名是object oriented design pattern,所以設計模式是指在物件導向...
- 5[ Day 1 ] 我為什麼想學設計模式( Design Pattern ) - iT 邦幫忙
在軟體工程中,設計模式(design pattern)是對軟體設計中普遍存在(反覆出現)的各種問題,所提出的解決方案。這個術語是由埃里希·伽瑪(Erich Gamma)等人在1990年代 ...