Go Design Patterns | Packt
文章推薦指數: 80 %
Go is a multi-paradigm programming language that has built-in facilities to create concurrent applications. Design patterns allow developers to efficiently ...
BrowseAll
FreeLearning
Signin
Subscribe
Aboutthisbook
Goisamulti-paradigmprogramminglanguagethathasbuilt-infacilitiestocreateconcurrentapplications.Designpatternsallowdeveloperstoefficientlyaddresscommonproblemsfacedduringdevelopingapplications.
GoDesignPatternswillprovidereaderswithareferencepointtosoftwaredesignpatternsandCSPconcurrencydesignpatternstohelpthembuildapplicationsinamoreidiomatic,robust,andconvenientwayinGo.
ThebookstartswithabriefintroductiontoGoprogrammingessentialsandquicklymovesontoexplaintheideabehindthecreationofdesignpatternsandhowtheyappearedinthe90’sasacommon"language"betweendeveloperstosolvecommontasksinobject-orientedprogramminglanguages.Youwillthenlearnhowtoapplythe23GangofFour(GoF)designpatternsinGoandalsolearnaboutCSPconcurrencypatterns,the"killerfeature"inGothathashelpedGoogledevelopsoftwaretomaintainthousandsofservers.
Withallofthisthebookwillenableyoutounderstandandapplydesignpatternsinanidiomaticwaythatwillproduceconcise,readable,andmaintainablesoftware.
Publicationdate:
February2017
Publisher
Packt
Pages
402
ISBN
9781786466204
DownloadcodefromGitHub
RelatedTags:
NewReleases
Django
AJAX
WebDevelopment
MostPopular
Chapter 1. Ready...Steady...Go!DesignPatternshavebeenthefoundationforhundredsofthousandsofpiecesofsoftware.SincetheGangOfFour(ErichGamma,RichardHelm,RalphJohnsonandJohnVlissides)wrotethebookDesignPatterns:ElementsofReusableObject-OrientedSoftwarein1994withexamplesinC++andSmalltalk,thetwenty-threeclassicpatternshavebeenre-implementedinmostofmajorlanguagesoftodayandtheyhavebeenusedinalmosteveryprojectyouknowabout.TheGangofFourdetectedthatmanysmallarchitectureswerepresentinmanyoftheirprojects,theystartedtorewritetheminamoreabstractwayandtheyreleasedthefamousbook.ThisbookisacomprehensiveexplanationandimplementationofthemostcommondesignpatternsfromtheGangofFourandtoday'spatternsplussomeofthemostidiomaticconcurrencypatternsinGo.ButwhatisGo...?
AlittlebitofhistoryOnthelast20years,wehavelivedanincrediblegrowthincomputerscience.Storagespaceshavebeenincreaseddramatically,RAMhassufferedasubstantialgrowth,andCPU'sare...well...simplyfaster.HavetheygrownasmuchasstorageandRAMmemory?Notreally,CPUindustryhasreachedalimitinthespeedthattheirCPU'scandeliver,mainlybecausetheyhavebecomesofastthattheycannotgetenoughpowertoworkwhiletheydissipateenoughheat.TheCPUmanufacturersarenowshippingmorecoresoneachcomputer.Thissituationcrashesagainstthebackgroundofmanysystemsprogramminglanguagesthatweren'tdesignedformulti-processorCPUsorlargedistributedsystemsthatactasauniquemachine.InGoogle,theyrealizedthatthiswasbecomingmorethananissuewhiletheywerestrugglingtodevelopdistributedapplicationsinlanguageslikeJavaorC++thatweren'tdesignedwithconcurrencyinmind.Atthesametime,ourprogramswerebigger,morecomplex,moredifficulttomaintainandwitha lotofroomforbadpractices.Whileourcomputershadmorecoresandwerefaster,wewerenotfasterwhendevelopingourcodeneitherourdistributedapplications.ThiswasGo'starget.Godesignstartedin2007bythreeGooglersintheresearchofaprogramminglanguagethatcouldsolvecommonissuesinlargescaledistributedsystemsliketheonesyoucanfindatGoogle.Thecreatorswere:RobPike:Plan9andInfernoOS.RobertGriesemer:WorkedatGoogle'sV8JavaScriptenginethatpowersGoogleChrome.KenThompson:WorkedatBelllabsandtheUnixteam.IthasbeeninvolvedindesigningofthePlan9operatingsystemaswellasthedefinitionoftheUTF-8encoding.In2008,thecompilerwasdoneandtheteamgotthehelpofRussCoxandIanLanceTaylor.Theteamstartedtheirjourneytoopensourcetheprojectin2009andinMarch2012theyreachedaversion1.0aftermorethanfiftyreleases.
InstallingGoAnyGoInstallationneedstwobasicthings:thebinariesofthelanguagesomewhereonyourdiskandaGOPATHpathinyoursystemwhereyourprojectsandtheprojectsthatyoudownloadfromotherpeoplewillbestored.Inthefollowinglines,wewillexplorehowtoinstallGobinariesinLinux,WindowsandOSX.ForadetailedexplanationofhowtoinstallthelatestversionofGo,youcanrefertotheofficialdocumentationathttps://golang.org/doc/install.LinuxToinstallGoinLinuxyouhavetwooptions:
Easyoption:Useyourdistributionpackagemanager:
RHEL/Fedora/CentosuserswithYUM/DNF:
sudoyuminstall-ygolang
Ubuntu/DebianusersusingAPTwith:
sudoapt-getinstall-ygolang
Advanced:Downloadingthelatestdistributionfrom
https://golang.org.
Irecommendusingthesecondanddownloadingadistribution.Go'supdatesmaintainsbackwardcompatibilityandyouusuallyshouldnotbeworriedaboutupdatingyourGobinariesfrequently.GoLinuxadvancedinstallationTheadvancedinstallationofGoinLinuxrequiresyoutodownloadthebinariesfromgolangwebpage.Afterentering
https://golang.org
,clicktheDownloadGobutton(usuallyattheright)someFeaturedDownloadsoptionisavailableforeachdistribution.SelectLinuxdistributiontodownloadthelateststableversion.NoteAt https://golang.orgyoucanalsodownloadbetaversionsofthelanguage.Let'ssaywehavesavedthetar.gz fileinDownloadsfoldersolet'sextractitandmoveittoadifferentpath.Byconvention,Gobinariesareusuallyplacedin/usr/local/godirectory:tar-zxvfgo*.*.*.linux-amd64.tar.gz
sudomvgo/usr/local/go
Onextractionremembertoreplaceasterisks(*)withtheversionyouhavedownloaded.NowwehaveourGoinstallationin/usr/local/gopathsonowwehavetoaddthebinsubfoldertoourPATHandthebinfolderwithinourGOPATH.mkdir-p$HOME/go/bin
With-pwearetellingbashtocreatealldirectoriesthatarenecessary.NowweneedtoappendbinfolderpathstoourPATH,appendthefollowinglinesattheendofyour~/.bashrc:exportPATH=$PATH:/usr/local/go/bin
Checkthatourgo/bin directoryisavailable:$goversion
Goversiongo1.6.2linux/amd64
WindowsToinstallGoinWindows,youwillneedadministratorprivileges.Openyourfavoritebrowserandnavigateto
https://golang.org
.OncethereclicktheDownloadGobuttonandselectMicrosoftWindowsdistribution.A*.msifilewillstartdownloading.ExecutetheMSIinstallerbydoubleclickingit.AninstallerwillappearaskingyoutoaccepttheEndUserLicenseAgreement(EULA)andselectatargetfolderforyourinstallation.WewillcontinuewiththedefaultpaththatinmycasewasC:\Go.OncetheinstallationisfinishedyouwillhavetoaddthebinaryGofolder,locatedinC:\Go\bintoyourPath.Forthis,youmustgotoControlPanelandselectSystemoption.OnceinSystem,selecttheAdvancedtabandclicktheEnvironmentvariablesbutton.Hereyou'llfindawindowwithvariablesforyourcurrentuserandsystemvariables.Insystemvariables,you'llfindthePathvariable.ClickitandclicktheEdit
buttontoopenatextbox.Youcanaddyourpathbyadding;C:\Go/binattheendofthecurrentline(notethesemicolonatthebeginningofthepath).InrecentWindowsversions(Windows10)youwillhaveamanagertoaddvariableseasily.MacOSXInMacOSXtheinstallationprocessisverysimilartoLinux.Openyourfavoritebrowserandnavigateto
https://golang.org
andclicktheDownloadGo.Fromthelistofpossibledistributionsthatappear,selectAppleOSX.Thiswilldownloada*.pkgfiletoyourdownloadfolder.AwindowwillguideyouthroughtheinstallationprocesswhereyouhavetotypeyouradministratorpasswordsothatitcanputGobinaryfilesin/usr/local/go/binfolderwiththeproperpermissions.Now,openTerminaltotesttheinstallationbytypingthisonit:$goversion
Goversiongo1.6.2darwin/amd64
Ifyouseetheinstalledversion,everythingwasfine.Ifitdoesn'tworkcheckthatyouhavefollowedcorrectlyeverysteporrefertothedocumentationat https://golang.org.Settingtheworkspace-LinuxandAppleOSXGowillalwaysworkunderthesameworkspace.Thishelpsthecompilertofindpackagesandlibrariesthatyoucouldbeusing.ThisworkspaceiscommonlycalledGOPATH.GOPATHhasaveryimportantroleinyourworkingenvironmentwhiledevelopingGosoftware.Whenyouimportalibraryinyourcodeitwillsearchforthislibraryinyour$GOPATH/src.ThesamewhenyouinstallsomeGoapps,binarieswillbestoredin$GOPATH/bin.Atthesame,allyoursourcecodemustbestoredinavalidroutewithin$GOPATH/srcfolder.Forexample,IstoremyprojectsinGitHubandmyusernameisSaydenso,foraprojectcalledminimal-mesos-go-frameworkIwillhavethisfolderstructurelike $GOPATH/src/github.com/sayden/minimal-mesos-go-frameworkwhichreflectstheURIwherethisrepoisstoredatGitHub:mkdir-p$HOME/go
The$HOME/gopathisgoingtobethedestinationofour$GOPATH.Wehavetosetanenvironmentvariablewithour$GOPATHpointingtothisfolder.Tosettheenvironmentvariable,openagainthefile$HOME/.bashrcwithyourfavoritetexteditorandaddthefollowinglineattheendofit:exportGOPATH=${HOME}/go
Savethefileandopenanewterminal.Tocheckthateverythingisworking,justwriteanechotothe$GOPATHvariablelikethis:echo$GOPATH
/home/mcastro/go
IftheoutputoftheprecedingcommandpointstoyourchosenGopath,everythingiscorrectandyoucancontinuetowriteyourfirstprogram.
StartingwithHelloWorldThiswouldn'tbeagoodbookwithoutaHelloWorldexample.OurHelloWorldexamplecan'tbesimpler,openyourfavoritetexteditorandcreateafilecalledmain.gowithinour$GOPATH/src/[your_name]/hello_worldwiththefollowingcontent:packagemain
funcmain(){
println("HelloWorld!")
}
Savethefile.Torunourprogram,opentheTerminalwindowofyouroperatingsystem:InLinux,gotoprogramsandfindaprogramcalledTerminal.InWindows,hitWindows+R,typecmdwithoutquotesonthenewwindowandhitEnter.InMacOSX,hitCommand+Spacetoopenaspotlightsearch,typeterminalwithoutquotes.TheterminalappmustbehighlightedsohitEnter.Onceweareinourterminal,navigatetothefolderwherewehavecreatedourmain.gofile.Thisshouldbeunderyour$GOPATH/src/[your_name]/hello_worldandexecuteit:gorunmain.go
HelloWorld!
That'sall.Thegorun[file]commandwillcompileandexecuteourapplicationbutitwon'tgenerateanexecutablefile.Ifyouwantjusttobuilditandgetanexecutablefile,youmustbuildtheappusingthe followingcommand:gobuild-ohello_world
Nothinghappens.Butifyousearchinthecurrentdirectory(lscommandinLinuxandMacOSX;anddirinWindows),you'llfindanexecutablefilewiththenamehello_world.Wehavegiventhisnametotheexecutablefilewhenwewrote-ohello_worldcommandwhilebuilding.Youcannowexecutethisfile:/hello_world
HelloWorld!
Andourmessageappeared!InWindows,youjustneedtotypethenameofthe.exefiletogetthesameresult.TipThegorun[my_main_file.go]commandwillbuildandexecutetheappwithoutintermediatefiles.
Thegobuild-o[filename]commandwillcreateanexecutablefilethatIcantakeanywhereandhasnodependencies.
IntegratedDevelopmentEnvironment-IDEAnIDE(IntegratedDevelopmentEnvironment)isbasicallyauserinterfacetohelpdevelopers,codetheirprogramsbyprovidingasetoftoolstospeedupcommontasksduringdevelopmentprocesslikecompiling,building,ormanagingdependencies.TheIDEsarepowerfultoolsthattakesometimetomasterandthepurposeofthisbookisnottoexplainthem(anIDElikeEclipsehasitsownbooks).InGo,youhavemanyoptionsbutthereareonlytwothatarefullyorientedtoGodevelopment LiteIDEandIntellijGogland.LiteIDEisnotthemostpowerfulthoughbutIntellijhasputlotsofeffortstomakeGoglandaveryniceeditorwithcompletion,debugging,refactoring,testing,visualcoverage,inspections,etc.CommonIDEsortexteditorsthathaveaGoplugin/integrationareasfollowing:IntelliJIdeaSublimeText2/3AtomEclipseButyoucanalsofindGopluginsfor:VimVisualStudioandVisualCodeTheIntelliJIdeaandAtomIDEs,forthetimeofthiswriting,hasthesupportfordebuggingusingaplugincalledDelve.TheIntelliJIdeaisbundledwiththeofficialGoplugin.InAtomyou'llhavetodownloadaplugincalledGo-plusandadebuggerthatyoucanfindsearchingthewordDelve.
TypesTypesgivetheusertheabilitytostorevaluesinmnemonicnames.Allprogramminglanguageshavetypesrelatedwithnumbers(tostoreintegers,negativenumbers,orfloatingpointforexample)withcharacters(tostoreasinglecharacter)withstrings(tostorecompletewords)and soon.Golanguagehasthecommontypesfoundinmostprogramminglanguages:TheboolkeywordisforBooleantypewhichrepresentsaTrueorFalsestate.Manynumerictypesbeingthemostcommon:
Theinttyperepresentsanumberfrom0to4294967295in32bitsmachinesandfrom0to18446744073709551615in64bits.Thebytetyperepresentsanumberfrom0to255.Thefloat32andfloat64typesarethesetofallIEEE-75464/-bitfloating-pointnumbersrespectively.Youalsohavesignedinttypelikerunewhichisanaliasofint32type,anumberthatgoesfrom-2147483648to2147483647andcomplex64andcomplex128whicharethesetofallcomplexnumberswithfloat32/float64realandimaginarypartslike2.0i.
Thestringkeywordforstringtyperepresentsanarrayofcharactersenclosedinquoteslike"golang"or"computer".Anarraythatisanumberedsequenceofelementsofasingletypeandafixedsize(moreaboutarrayslaterinthischapter).Alistofnumbersorlistsofwordswithafixedsizeisconsideredarrays.Theslicetypeisasegmentofanunderlyingarray(moreaboutthislaterinthischapter).Thistypeisabitconfusingatthebeginningbecauseitseemslikeanarraybutwewillseethatactually,theyaremorepowerful.Thestructuresthataretheobjectsthatarecomposedofanotherobjectsortypes.Thepointers(moreaboutthislaterinthischapter)arelikedirectionsinthememoryofourprogram(yes,likemailboxesthatyoudon'tknowwhat'sinside).Thefunctionsareinteresting(moreaboutthislaterinthischapter).Youcanalsodefinefunctionsasvariablesandpassthemtootherfunctions(yes,afunctionthatusesafunction,didyoulikeInceptionmovie?).Theinterfaceisincrediblyimportantforthelanguageastheyprovidemanyencapsulationandabstractionfunctionalitiesthatwe'llneedoften.We'lluseinterfacesextensivelyduringthebookandtheyarepresentedingreaterdetaillater.Themaptypesareunorderedkey-valuestructures.Soforagivenkey,youhaveanassociatedvalue.ThechannelsarethecommunicationprimitiveinGoforconcurrencyprograms.We'lllookonchannelswithmoredetailonChapter8,DealingwithGo'sCSPconcurrency.
VariablesandconstantsVariablesarespacesincomputer'smemorytostorevaluesthatcanbemodifiedduringtheexecutionoftheprogram.Variablesandconstantshaveatypeliketheonesdescribedinprecedingtext.Although,youdon'tneedtoexplicitlywritethetypeofthem(althoughyoucandoit).ThispropertytoavoidexplicittypedeclarationiswhatiscalledInferredtypes.Forexample://Explicitlydeclaringa"string"variable
varexplicitstring="Hello,I'maexplicitlydeclaredvariable"
Herewearedeclaringavariable(withthekeywordvar)calledexplicitofstringtype.Atthesametime,wearedefiningthevaluetoHelloWorld!.//Implicitlydeclaringa"string".Typeinferred
inferred:=",I'maninferredvariable"
Butherewearedoingexactlythesamething.Wehaveavoidedthevarkeywordandthestringtypedeclaration.Internally,Go'scompilerwillinfer(guess)thetypeofthevariabletoastringtype.Thiswayyouhavetowritemuchlesscodeforeachvariabledefinition.Thefollowinglinesusethereflectpackagetogatherinformationaboutavariable.Weareusingittoprintthetypeof(the TypeOf variableinthecode)ofbothvariables:fmt.Println("Variable'explicit'isoftype:",
reflect.TypeOf(explicit))
fmt.Println("Variable'inferred'isoftype:",
reflect.TypeOf(inferred))
Whenweruntheprogram,theresultisthefollowing:$gorunmain.go
Hello,I'maexplicitlydeclaredvariable
Hello,I'maninferredvariable
Variable'explicit'isoftype:string
Variable'inferred'isoftype:string
Asweexpected,thecompilerhasinferredthetypeoftheimplicitvariabletostringtoo.Bothhavewrittentheexpectedoutputtotheconsole.
OperatorsTheoperatorsareusedtoperformarithmeticoperationsandmakecomparisonsbetweenmanythings.ThefollowingoperatorsarereservedbyGolanguage.
Mostcommonlyusedoperatorsarethearithmeticoperatorsandcomparators.Arithmeticoperatorsareasfollowing:The+operatorforsumsThe-operatorforsubtractionsThe*operatorformultiplicationsThe/operatorfordivisionsThe%operatorfordivisionremaindersThe++operatortoadd1tothecurrentvariableThe--operatortosubtract1tothecurrentvariableOntheotherside,comparatorsareusedtocheckthedifferencesbetweentwostatements:The==operatortocheckiftwovaluesareequalThe!=operatortocheckiftwovaluesaredifferentThe>operatortocheckifleftvalueishigherthanrightvalueThe
延伸文章資訊
- 1All Design Patterns in Go (Golang)
A curated list of design patterns implemented in Go. ... in learning Golang, then for that we hav...
- 2Design Patterns in Go - Medium
Strategy Design Pattern: The Strategy pattern basically allows an object to select and execute at...
- 3Design Patterns in Go - Refactoring.Guru
The Catalog of Go Examples · Creational Patterns · Abstract Factory · Builder · Factory Method · ...
- 4[Golang] Design Pattern | PJCHENder 未整理筆記
[Golang] Design Pattern. golang. Functional Options. 資料來源:GO 程式設計模式:FUNCTIONAL OPTIONS @ 陳皓. 在Go...
- 5senghoo/golang-design-pattern: 设计模式Golang实现 - GitHub
设计模式Golang实现-《研磨设计模式》读书笔记. Contribute to senghoo/golang-design-pattern development by creating an...