Factory Method pattern in Go - Travix Engineering

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

Factory Method pattern in Go · The struct used for the implementation is defined as private ; · The method accepts the options struct as a value ... SigninTravixEngineeringAboutWebsiteFactoryMethodpatterninGoRalphLigtenbergFollowMay8,2017·2minreadWhenyou’veprogrammedinGoforawhile,youstarttorecognizesomedesignpatterns.OneofthemthatI’veusedforacoupleofmonthsnowistheFactoryMethod.Althoughthisdesignpatternmightseemabittrivial,it’sactuallyasmartwaytohideimplementationdetails.Asyoumightalreadyknow,interfacesinGoenforceyoutoseparateactionsfromdata.ThisisdonebyamechanismcalledDuckTyping,whichshouldringabellifyou’refamiliarwithPython.TheFactoryMethodenablesyoutocombinebothactionsanddataintoasinglestructandexposeonlytheinterface.Takealookatthiscodesample:Notethefollowingdetails:Thestructusedfortheimplementationisdefinedasprivate;Themethodacceptstheoptionsstructasavalueinsteadofapointer,whichimpliesweonlywanttouseitforreading;Whentheimplementationdoesn’tmatchtheinterface,theFactoryMethod’sreturnstatementwilltriggeracompilererror.BecausetheFactoryMethodimplicitlychecksthecorrectnessoftheimplementationoftheinterface,younolongerneedtoincludetheinterfaceasaproperty,likeinthissnippet:AnotheradvantageisthattheimplementationoftheFactoryMethodfacilitatesDependencyInjection.Youcanaddotherinterfacestothemethod’sparameterstoincludetheminyourprivatestruct.Thishelpskeepingyourcodeunit-testable.Youcanalsocreatemultipleimplementationsofthesameinterface.ChooseeithertocreateadistinctFactoryMethodforeachversion,oranall-in-onesolutionwheretheimplementationtypedependsontheparameters.Here’ssomemorerelevantreadingmaterial:https://medium.com/@matryer/golang-advent-calendar-day-one-duck-typing-a513aaed544dhttp://txt.fliglio.com/2015/04/di-duck-typing-and-clean-code-in-go/http://blog.ralch.com/tutorial/design-patterns/golang-factory-method/TravixEngineeringBlogbytheengineersbehindTravix.comFollow161ThankstoAlexMiranda. GolangProgrammingGoDesignPatternsInterfaces161 claps161WrittenbyRalphLigtenbergFollowAgilesolutiondeveloper,part-timeScrumMaster,Rubberduck,Boyscoutrulepractitioner,CleanCoder,communitybuilderandideacatalyst.FollowTravixEngineeringFollowBlogbytheengineersbehindTravix.comFollowWrittenbyRalphLigtenbergFollowAgilesolutiondeveloper,part-timeScrumMaster,Rubberduck,Boyscoutrulepractitioner,CleanCoder,communitybuilderandideacatalyst.TravixEngineeringFollowBlogbytheengineersbehindTravix.com



請為這篇文章評分?