Design Patterns: Factory Method in Go - Refactoring.Guru

文章推薦指數: 80 %
投票人數:10人

Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes. Hey,Ihavejustreducedthepriceforallproducts.Let'sprepareourprogrammingskillsforthepost-COVIDera.Checkitout»   /DesignPatterns /FactoryMethod /Go FactoryMethodinGo Factorymethodisacreationaldesignpatternwhichsolvestheproblemofcreatingproductobjectswithoutspecifyingtheirconcreteclasses. FactoryMethoddefinesamethod,whichshouldbeusedforcreatingobjectsinsteadofdirectconstructorcall(newoperator).Subclassescanoverridethismethodtochangetheclassofobjectsthatwillbecreated. Ifyoucan’tfigureoutthedifferencebetweenvariousfactorypatternsandconcepts,thenreadourFactoryComparison. LearnmoreaboutFactoryMethod Navigation  Intro  ConceptualExample  i­Gun  gun  ak47  musket  gun­Factory  main  output ConceptualExample It’simpossibletoimplementtheclassicFactoryMethodpatterninGoduetolackofOOPfeaturessuchasclassesandinheritance.However,wecanstillimplementthebasicversionofthepattern,theSimpleFactory. Inthisexample,we’regoingtobuildvarioustypesofweaponsusingafactorystruct. First,wecreatetheiGuninterface,whichdefinesallmethodsagunshouldhave.ThereisagunstructtypethatimplementstheiGuninterface.Twoconcreteguns—ak47andmusket—bothembedgunstructandindirectlyimplementalliGunmethods. ThegunFactorystructservesasafactory,whichcreatesgunsofthedesiredtypebasedonanincomingargument.Themain.goactsasaclient.Insteadofdirectlyinteractingwithak47ormusket,itreliesongunFactorytocreateinstancesofvariousguns,onlyusingstringparameterstocontroltheproduction. iGun.go:Productinterface packagemain typeiGuninterface{ setName(namestring) setPower(powerint) getName()string getPower()int } gun.go:Concreteproduct packagemain typegunstruct{ namestring powerint } func(g*gun)setName(namestring){ g.name=name } func(g*gun)getName()string{ returng.name } func(g*gun)setPower(powerint){ g.power=power } func(g*gun)getPower()int{ returng.power } ak47.go:Concreteproduct packagemain typeak47struct{ gun } funcnewAk47()iGun{ return&ak47{ gun:gun{ name:"AK47gun", power:4, }, } } musket.go:Concreteproduct packagemain typemusketstruct{ gun } funcnewMusket()iGun{ return&musket{ gun:gun{ name:"Musketgun", power:1, }, } } gunFactory.go:Factory packagemain import"fmt" funcgetGun(gunTypestring)(iGun,error){ ifgunType=="ak47"{ returnnewAk47(),nil } ifgunType=="musket"{ returnnewMusket(),nil } returnnil,fmt.Errorf("Wrongguntypepassed") } main.go:Clientcode packagemain import"fmt" funcmain(){ ak47,_:=getGun("ak47") musket,_:=getGun("musket") printDetails(ak47) printDetails(musket) } funcprintDetails(giGun){ fmt.Printf("Gun:%s",g.getName()) fmt.Println() fmt.Printf("Power:%d",g.getPower()) fmt.Println() } output.txt:Executionresult Gun:AK47gun Power:4 Gun:Musketgun Power:1 Basedon:GolangByExample Readnext DesignPatterns:PrototypeinGo  Return  DesignPatterns:BuilderinGo FactoryMethodinOtherLanguages Archivewithexamples BuytheeBookDiveIntoDesignPatternsandgettheaccesstoarchivewithdozensofdetailedexamplesthatcanbeopenedrightinyourIDE. Learnmore… Facebook Twitter Language English Español Français Polski PortuguêsBrasileiro Русский Українська 中文 Contactus Login EnglishEnglish EspañolEspañol FrançaisFrançais PolskiPolski PortuguêsBrasileiroPortuguês-Br РусскийРусский УкраїнськаУкраїнська 中文中文 PremiumContent DesignPatternseBook RefactoringCourse Refactoring WhatisRefactoring Cleancode Technicaldebt Whentorefactor Howtorefactor Catalog 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 Refactorings 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 DealingwithGeneralization PullUpField PullUpMethod PullUpConstructorBody PushDownMethod PushDownField ExtractSubclass ExtractSuperclass ExtractInterface CollapseHierarchy FormTemplateMethod ReplaceInheritancewithDelegation ReplaceDelegationwithInheritance DesignPatterns WhatisaPattern What’sadesignpattern? Historyofpatterns WhyshouldIlearnpatterns? Criticismofpatterns Classificationofpatterns Catalog CreationalPatterns FactoryMethod AbstractFactory Builder Prototype Singleton StructuralPatterns Adapter Bridge Composite Decorator Facade Flyweight Proxy BehavioralPatterns ChainofResponsibility Command Iterator Mediator Memento Observer State Strategy TemplateMethod Visitor CodeExamples C# C++ Go Java PHP Python Ruby Swift TypeScript Login Contactus



請為這篇文章評分?