Observer Pattern In Golang - Medium

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

Observer Pattern In Golang · The What · subscriber and the website publishes notifications only for topics that you have registered hence the website can be ... GetstartedOpeninappAshutoshKumarSigninGetstarted46FollowersAboutGetstartedOpeninappObserverPatternInGolangAshutoshKumarJul26,2020·6minreadInthisblogpost,Iamgoingtowriteaboutoneimportantobject-orienteddesignpatterni.e.observerpattern.IhavedrawninspirationfromtheHeadFirstDesignPatternsbookthatexclusivelyexplainsobject-orientedprinciplesbasedonJava.LetusseehowwecanapplythisobserverdesignpatterninGolang.Thistutorialisorganizedintothefollowingthreesections:1.TheWhat—Itdescribeswhatisanobserverpattern.2.TheHow—HowwecanimplementitinGolang?3.TheWhy—Whyorwhenweneedit?TheWhatSupposethereexistsatechnewsaggregationwebsite(e.gReddit)andyouhaveregisteredonittoreadaboutcooltech/engineeringstuff.Itispossiblethatyouareinterestedinaparticulartechnologyandyouwouldnotliketomissanynews/postaboutitfromthewebsite.Forthat,thewebsitegivesyouafeaturetoregisterfornotificationsfortechtopicsthatareofyourinterestandifthereareanynews/postsaboutthatspecifictopicyouwillbenotified.Thisisawesome!Ifyoulookattheabovestoryclosely,youhaveregistered/subscribedforsomespecifictopicsandhenceyoucanbecalledasubscriberandthewebsitepublishesnotificationsonlyfortopicsthatyouhaveregisteredhencethewebsitecanbecalledapublisher.Ifyouunderstandtheabovestory,youunderstandtheobserverpattern.Ifwetalkintermsofobjects,subscriberobjectsgetanupdateofdatawheneverthepublisher’sdatachange.Letusnowjumpintoseeacodeexampleandthenthingswillbemoreclear.Publisher-SubscribersNote:Publisherscanalsobecalledsubjectsandsubscriberscanalsobecalledobservers.TheHowInthissection,wewillbuildasamplecodeinGolangtoillustratetheobserverpattern.Letuslookatthefollowingstatementstounderstandwhatwewanttobuild.WewanttohaveaSubjectobjectandwheneverthedataofthisSubjectobjectchangeswewanttonotifyalltheregisteredobservers.Itshouldbepossiblefortheobserverobjectstoregisterandde-registerfromthesubject.RelationshipDiagramTheSubjectintherelationshipdiagramisaninterfaceandaconcretesubjectshouldimplementthemethodsofthesubjectinterface.AconcretesubjectisnothingbutaGolangstructurethatisapublisher.OneexampleofaconcretesubjectcouldbeScoreUpdaterthatsendsupdatesofagamescoretoregisteredconcreteobservers.HereconcreteobserverscanbeUsers.NoticethatScoreUpdaterandUsersareGolangstructures.Inourexample,ScoreUpdateristheSimpleSubject,andUseristheSimpleObserver.ScoreUpdaterhasalistofUserandUserhasaSocreUpdater.Noticethebidirectionalrelationship.Thefollowingcodewillhelpunderstandandclarify.Thecodeiscommentedextensivelytomakeisunderstandable.packagemain//Subjectinterfaceisimplementedbyconcretesubjects/publisherstypeSubjectinterface{RegisterObserver(oObserver)RemoveObserver(oObserver)NotifyObserver()}//ScoreUpdaterisaconcretesubject/publisherthatimplements//subjectinterfacetypeScoreUpdaterstruct{//scoreisthecurrentscoreofagamebeingplayed.scoreint//observerListcontainsregisteredsubscribers/observers//towhichthe//updatesofthescorewillbesentoncethescorechanges.//NoticethatthetypeisObserverinterfaceandnotthe//concretetypeUser.observerList[]Observer}//Observerinterfaceisimplementedbyconcrete//oservers/subscriberstypeObserverinterface{Update(valueint)}//Userisaconcreteobserver/subscriberthatimplementssubjectinterfacetypeUserstruct{//nameoftheusernamestring//scoreofthegameknowntotheuserscoreint//subjectinwhichtheuserisinterestedin.//NoticethatthetypeisinterfaceSubjectandnottheconcrete//typeScoreUpdatersimpleSubjectSubject}//NewUserreturnsaninstanceofuser.//IttakessubjectasanargumentfuncNewUser(ssSubject,namestring)*User{newUser:=&User{name:name,simpleSubject:ss,}newUser.simpleSubject.RegisterObserver(newUser)returnnewUser}//Updateupdatesthescorevalueknowntotheuser//andcallsdisplayfunc(u*User)Update(scoreint){u.score=scoreu.display()}//displayprintsthecurrentscorevaluefunc(u*User)display(){fmt.Printf("%sreceivedscoreupdates:%d\n",u.name,u.score)}//NewScoreUpdaterreturnsanisntanceofScoreUpdaterfuncNewScoreUpdater()*ScoreUpdater{return&ScoreUpdater{score:0,observerList:make([]Observer,0),}}//RegisterObserverregistersanobserverprovidedinthe//argument.func(su*ScoreUpdater)RegisterObserver(oObserver){su.observerList=append(su.observerList,o)}//RemoveObserverremovesanobserverprovidedintheargument.func(su*ScoreUpdater)RemoveObserver(oObserver){found:=falsei:=0for;i



請為這篇文章評分?