Observer Design Pattern in Golang with an Example

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

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



請為這篇文章評分?