The Observer Pattern In Go - Level Up Coding

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

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.



請為這篇文章評分?