Observer Pattern In Golang - Medium
文章推薦指數: 80 %
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
延伸文章資訊
- 1The Observer Design Pattern In Go - Morioh
The Observer design pattern is a fundamental tool for any capable software engineer. In one sente...
- 2Observer Pattern In Golang - Medium
Observer Pattern In Golang · The What · subscriber and the website publishes notifications only f...
- 3Observer Design Pattern in Golang with an Example
Observer Design Pattern is a software design pattern that lets you define a subscription mechanis...
- 4Generator Pattern and Observer Pattern - Part Two - YouTube
tensorprogramming #golang #designpatternsIn this tutorial, we take a look at the Generator patter...
- 5Observer pattern in Go language - Stack Overflow
The Go way to implement the Observer design pattern - Stack ...