The Observer Pattern In Go - Level Up Coding
文章推薦指數: 80 %
The Observer Pattern In Go ... A fundamental design pattern every software engineer needs to know. The Observer design pattern is a fundamental ... SigninWRITEFORUSDAYTRADERDASHBOARD🚀CodingInterviewCourse→TheObserverPatternInGoIsraelMilesFollowNov18,2020·5minreadAfundamentaldesignpatterneverysoftwareengineerneedstoknow.TheObserverdesignpatternisafundamentaltoolforanycapablesoftwareengineer.Inonesentence,itconsistsofobserversthatpaycloseattentiontosubjectsthatchangetheirstate.Inthistutorial,wewillexploretheusecases,UMLdiagramandimplementationinmycurrentfavoriteprogramminglanguage—Go.Note:Theterminologycanvaryasanobserver/subscriberorasasubject/topic/publisher.Theyareallthesame,butIwillbeusingobserverandsubjectsinthisarticle.UseCasesTherealworldexamplesoftheobserverdesignpatternareendless.Theyinclude:Socialmediaplatforms—friendscanfollowotherfriendstoshareupdateswitheachother.Mediumitselfcouldusethispattern!Newsplatforms—peoplesubscribetonewsstations(WashingtonPostforexample)andarenotifieddaily/weeklyalsowithbreakingnewsevents.RoboticOperatingSystem(ROS)—notanactualoperatingsystem,butROSactuallyhasbasiccommunicationwithitsrobotsbuiltoffoftheobserverpatternwithpublishersandsubscriberstotransferinformation.Andsomanymore!UMLDiagramThankfullywehaveasimplediagramtoanalyze.YoucangetvariationswheretheSubjectisnotaninterface,butIthinkkeepingboththeSubjectandtheObserverasinterfacesgreatlyimprovestheflexibilityofyourcodeandprovidecontractstoscalefrom.FromyourstrulyStartingfromtopleft,theSubjectisnormallylistedasanabstractclass,butGodoesn’thaveclassessoweinsteadlabelitasaninterface.TheConcreteSubjectwillimplementthisinterfacewiththissameprocessapplyingtoObservers.WehaveAttach()andDetach()methodsintheSubjectthatbothtakeinanObserverobject.ThereisacompositerelationshipbetweenSubjectandObserver,meaningthatwecanhaveaSubjectwithzerotomanyObservers.FurthermoreboththeConcreteSubjectandConcreteObserverimplementthetwointerfaceswithdashedlines,ratherthaninheritfromaclasswhichwouldbefilledinlines(becausethisisGoafterall).Finallytheconcreteobjectshaveprivatestatesassignedtothemwhichcanthenbeaccessedandalteredbythepublicmethodsinordertomaintainintegrity.Note:Godoesn’thavepublicorprivatekeywords.Instead,publicmethodsstartwithacapitalletterandprivatemethodsstartwithalowercaseletter.ImplementationinGoInthisexamplewearegoingtocreateaprogramthathassensorstodetectchangesintemperaturewithweatherstationstobroadcastinformation.ThesensorswillactasanimplementationoftheSubjectinterface,whilethestationswillbeobserversoftheweathersensors.Let’smakebasicstructurethatwillconsistof3files.$mkdirobserver-pattern-go$cdobserver-pattern-go$touchmain.goobserver.gosubject.goWewillfirstworkontheobserverimplementation.observer.goOurObserverinterfaceissimple,wejustneedtoimplementastructwiththeUpdate()methodincluded.TheWeatherStationwillhandlethis.Sincetherearen’tclassesinGo,wewillcreateourownformofaconstructorasseenonlines9–11whichreturnareferencetoanewWeatherStationobject.TheWeatherStationstructsimplyhasanameasitsonlyproperty.WethenimplementtheObserverinterfacebyimplementingtheUpdate()method.ThisisachievedbyinjectingareferencetoaWeatherStationobjectintothefunctiononline17.NowWeatherStationimplementstheUpdate()methodandtheObserverinterfaceishappy.TheUpdate()functionwillsimplyreportthetemperatureandwhetherthedayishotmildorcold.subject.goTheWeatherSensorwillimplementtheSubjectinterfacebydefiningtheNotifyAll()method.TheWeatherSensoralsohasadditionalfunctionalityinthatithasaslice[]*WeatherStationwhichstoresreferencestoweatherstations.TheSubjectkeywordonline18meansweareextendingtheinterfacetothisstruct.Finallythereisalsoastatepropertytemperature.WethenalsoimplementtwomethodsaddStation()andremoveStation()whichbothtakeareferencetoaWeatherStationasitsparameter.Addingaweatherstationisassimpleasappendingtotheobject’sslice.However,removingaweatherstationisactuallyabitmoreinvolved.Referencethecodebelow,butI’msurprisedGodoesn’thaveasimplermethodtojusthandlethisforus.TheNotifyAll()methodimplementationsimplyloopsoverallweatherStationsandcallstheirownUpdate()method,whichwedefinedearlierasstatingwhetherthedaywashot,coldormild.OfcoursewealsohaveGo’sversionofaconstructoronlines46–50thatreturnsanewreference&WeatherSensorthatdefinestheinitialtemperature.ThefunctiongetRandomTemperature()isjustahelperfunctionandreturnarandomintegerbetweenthegivenrangeasdefinedabove.NoticehowwheneverwecallthemethodChangeTemperature(),wepassastructreference*WeatherSensor.Beforeweprintoutthatit’sanewday,wechangethetemperatureofthesensorandthenwenotifyallobservers(weatherstations)aboutthechangewithNotifyAll().main.goFinallywehaveourmainGofilethatwillserveastheclienttoexecuteourcode.Nothingcrazyhere,wejustinitializeourobjectsandtheninteractwiththemusingourfancynewObserverpattern!Youcanruntheprojectwiththecommandintheobserver-pattern-godirectory:$gorun*.goDenverWeatherStationreporting:Thetemperatureis101F,itwillbeahotday!VailWeatherStationreporting:Thetemperatureis101F,itwillbeahotday!CheyenneWeatherStationreporting:Thetemperatureis57F,itwillbeamildday.It'sanewday!DenverWeatherStationreporting:Thetemperatureis17F,itwillbeacoldday!VailWeatherStationreporting:Thetemperatureis17F,itwillbeacoldday!It'sanewday!CheyenneWeatherStationreporting:Thetemperatureis29F,itwillbeacoldday!It'sanewday!DenverWeatherStationreporting:Thetemperatureis1F,itwillbeacoldday!DenverWeatherStationreporting:Thetemperatureis1F,itwillbeacoldday!CheyenneWeatherStationreporting:Thetemperatureis29F,itwillbeacoldday!YoushouldnowhaveagreatfoundationalunderstandingoftheObserverPatterninGo,congratulations!Thereisplentytoimproveonhereforyourownselfstudysuchasunittesting,implementingadditionalsensorsandfunctionalityorrefactoringinvokermethodsintothecodebase.Ialsothinksomeinterestingnewfeaturescouldbetorandomlygeneratethesensorsthemselves,andthenaveragethemforyourweatherreport.Youcouldgoasfarascreatingarandomizedfunctionyourselfandtrytopredicttheweather!Thepossibilitiesareendless,butthekeypieceisthatyoucaneasilyexpandthiscodebasenowthatyouhavetheObserverpatternbackingit.Ihopeyouenjoyedthisarticle,ifthereisanythingyoulikedorwanttohearmoreaboutIencourageyoutoleaveacommentbelow.Thanksforreading!LevelUpCodingCodingtutorialsandnews.Follow2603GolangTutorialProgrammingSoftwareDevelopmentDesign260 claps2603WrittenbyIsraelMilesFollowSoftwareEngineer@MicrosoftQuantumComputing.Iwriteabouttech,life,andhowtobebetterthanthedaybefore.FollowLevelUpCodingFollowCodingtutorialsandnews.Thedeveloperhomepagegitconnected.com&&skilled.devFollowWrittenbyIsraelMilesFollowSoftwareEngineer@MicrosoftQuantumComputing.Iwriteabouttech,life,andhowtobebetterthanthedaybefore.LevelUpCodingFollowCodingtutorialsandnews.Thedeveloperhomepagegitconnected.com&&skilled.devMoreFromMediumAreYouaBadProblemSolver? — Herearethe8TipstobeaMasteratProblem-Solving.VishnuaraviinLevelUpCodingJava8Bliss:OptionalKnoldusInc.inKnoldus-TechnicalInsightsMigratingPostgreSQLstandaloneinstancetoAurora(AmazonRDS)PavelTsiukhtsiayeuRaisingthebarfortheRoute53consoleBenSchaechterYouDon’tHavetoParticipateinHacktoberfestShannonCrabillDatadriventestingusingkarateDSLKnoldusInc.LIKEMIKE(2020)OmarGonzalezFunctionalJava:FunctionaldatastructurewithVavrKnoldusInc.
延伸文章資訊
- 1design-pattern-golang/observer.go at master - GitHub
package observer. import "fmt". type Subject struct {. observers []Observer. context string. } fu...
- 2Go observer pattern example - gist GitHub
Go observer pattern example. GitHub Gist: instantly share code, notes, and snippets.
- 3Observer pattern in Go language - Stack Overflow
The Go way to implement the Observer design pattern - Stack ...
- 4Reacting to File Changes Using the Observer Design Pattern ...
To illustrate the observer pattern in Go, we are going to watch for changes in a local folder. Ev...
- 5Observer Design Pattern in Go (Golang)
Observer Design Pattern is a behavioral design pattern. This pattern allows an instance (called s...