Observer Design Pattern in Golang with an Example
文章推薦指數: 80 %
Observer Design Pattern is a software design pattern that lets you define a subscription mechanism to notify multiple objects about any ... SigninWRITEFORUSDAYTRADERDASHBOARD🚀CodingInterviewCourse→ObserverDesignPatterninGolangwithanExampleImplementobserverdesignpatterninGolangJerryAnFollowNov3·4minreadPhotobyClayBanksonUnsplashObserverDesignPatternisasoftwaredesignpatternthatletsyoudefineasubscriptionmechanismtonotifymultipleobjectsaboutanyeventsthathappentotheobjectthey’reobserving.Itisoneofthesimplestandwidelyusedpatterns.Ithasmanyreal-worldusecases.Thefollowingaresomeofthemostcommonones.Newspapersubscriptionbetweennewscompaniesandsubscribers.Cellphonealarmtowakeupatsomespecifiedtime.Mobilewetherapplicationupdatestemperatureandhumiditycontinuously.Thestocktradingapplicationdisplaysthelateststockprices.Feelalittlecuriousabouttheobserverpattern?Let’sgearupandunderstandmoreaboutit.SubjectandObserverSubjectandObserversRelationship,drawnbytheauthorThetwoimportantconceptsofobserverpatternareSubjectandObserver.Observer:itistheobjectthatisinterestedinthesubjectSubject:itistheobjectthatisbeingobserved.Let’sexplainwithanexample.Supposesyouareinterestedinthenewsandwanttosubscribetothelatestnews.Herethereisanewsaggregator.Itcollectsthenewsfromvarioussourcesandthenpublishesthenewstoyou.Intheexample,thenewsaggregatoristhesubjectandyouareoneoftheobservers.Everytimetheaggregatorupdatesthenews,itwillnotifyallthesubscribersofthenews.Therelationshipbetweensubjectandobserverisone-to-many.ItmeansasubjectmaintainsalistofObservers.Whenthesubjectperceivessomestatechanges,itwillnotifyalltheobserversofthechange.That’swhyweclassifythispatternasabehavioralcategory.ImplementationinGoSupposeyouareinterestedinthestockmarket.Youhavethefollowingneeds:Youwanttokeeptrackofthestockpricesofaparticularcompany(e.g.AppleInc).Youwouldnotliketomissanystockpriceupdateespeciallyifthepriceisdroppingtoacertainpoint.Youwouldliketobenotifiedofallthestockpriceupdates.NowyoucanusetheObserverpatterntoimplementthis.Itisawesome!UMLdiagramThediagramaboveistheUMLforobserverpattern.Itishelpfulforustogetawholepictureofalltheobjects.Nowlet’sfirstconcentrateontheSubjectandObserverInterface.observer-subject-interfaceThesubjectinterfacedefinesthethreenecessarymethodsignatures.attachanddetachareusedtoattachanddetachanobserverfromthesubject.notifyisusedtonotifyallobserversofthesubject.TheobserverinterfacedefinesamethodsignatureUpdate.Itwillbetriggeredbythesubjectwhenacertainconditionismatched.Next,wecreateaconcreteobserverStockObserverthatimplementstheObserverinterface.concreteobserverSimilarly,wecreateaconcretesubjectStockMonitorthatimplementstheSubjectinterface.WealsodefinesomeinternalfieldsandmethodsfortheStockMonitorobject.observersdefinesasliceofobserversthatareattachedtothestockMonitorobjecttickerdefinesthetickerofacertainstock(e.g.AAPL)pricedefinesthepriceofacertainstocksetPriceisusedtosetthepriceofastockStringisusedtoprintthesubject’sinternalstatesFinally,herecomesthemainfile.mainfileInthispartWecreatetwoobservers,observerAandobserverB.AttachthemtothestockMonitor.ChangethepriceofthestockMonitor.WeseethatobserverAandobsererBarebothnotified.DetachobserverAfromthestockMonitorandchangethestockprice.WecanseethatonlyobserverBisnotified.LooseCouplingConsiderationsIntheObserverpattern,theSubjectandObserverarelooselycoupled.Subjectonlyknowsabouttheobserverandnotviceversa.TheobservercanbeattachedtomultiplesubjectsThenewobservercanbeattachedtothesubjectatanytime.Itwillbenotifiedofallthechangesafteritisattached.Detachinganobserverfromthesubjectwillnotnotifytheobserverofthechanges.Foundthisarticleuseful👏?Checkoutmyotherarticlesbelow!SOLIDPrinciplesinGolangExplainedwithExamplesTheSOLIDprinciplesarenotnewtoexperiencedprogrammers.Theygiveusguidelinesonhowtoarrangefunctionsand…levelup.gitconnected.comHowDoGolangChannelsWorkUnderstandingInnerworkingsoftheGolangChannelslevelup.gitconnected.comLevelUpCodingCodingtutorialsandnews.Follow87DesignPatternsGolangProgrammingSoftwareDevelopmentDataScience87 claps87WrittenbyJerryAnFollowDeveloperinChina,AIandmachinelearningenthusiast.TosupportmejoinMedium:https://jerryan.medium.com/membershipFollowLevelUpCodingFollowCodingtutorialsandnews.Thedeveloperhomepagegitconnected.com&&skilled.devFollowWrittenbyJerryAnFollowDeveloperinChina,AIandmachinelearningenthusiast.TosupportmejoinMedium:https://jerryan.medium.com/membershipLevelUpCodingFollowCodingtutorialsandnews.Thedeveloperhomepagegitconnected.com&&skilled.devMoreFromMediumLocustexperiments — FeedingthelocustsKarolBrejnainLocust.ioexperimentsSelf-TaughtDeveloper:HowToBecomeABetterFront-EndDeveloper4/5 — BootstrapForYour…AnnAdayaAchievingterraformDRYnesswithansibleandJavadockeroptimizationfrancisBuildingSearchFeatureUsingtheSQLLIKEOperatorDanielPericichIntroductiontoSQLAshwinP💻MyWebDevelopmentVSCodeSettings,theme,Extensions,tipsandtricksMichaelLazarskiNewproposedswitchexpressionsinJavaJDK12AshutoshShashiGettingCodeCoverageshowingInSonarCloudJoshDadakinPurplebricksDigital
延伸文章資訊
- 1The Observer Design Pattern In Go - Morioh
The Observer design pattern is a fundamental tool for any capable software engineer. In one sente...
- 2Observer Design Pattern in Go (Golang)
Observer Design Pattern is a behavioral design pattern. This pattern allows an instance (called s...
- 3Reacting 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...
- 4Observer pattern in Go language - Stack Overflow
The Go way to implement the Observer design pattern - Stack ...
- 5Go observer pattern example - gist GitHub
Go observer pattern example. GitHub Gist: instantly share code, notes, and snippets.