Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Observer pattern is used when there isone to many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically. Observer pattern falls under behavioural pattern category.
Example: a Youtube Channel and its subscribers
It is also called pub sub model

Whenever new contents in the youtube channel is added or existing content is modified, all the subscribers of the youtube channel will be notified

Let's understand the same example

observer

Subject orYoutubeChannel

packagePatterns.Behavioral.observer;importjava.util.ArrayList;importjava.util.List;publicclassYouTubeChannelSubject{privateStringchannelName;privateList<String>contents;List<Observer>subscriberObservers;publicYouTubeChannelSubject(){this.channelName="Mr.Beast";contents=newArrayList<>();subscriberObservers=newArrayList<>();}publicvoidaddNewContent(Stringname){contents.add(name);//notify all listenersnotifySubscriberObserver();}publicvoidremoveContent(Stringname){if(contents.contains(name)){contents.remove(name);//notify all listenersnotifySubscriberObserver();}}publicList<String>getContents(){returnthis.contents;}publicStringgetChannelName(){returnthis.channelName;}publicvoidaddObserver(Observerobserver){this.subscriberObservers.add(observer);}publicvoidremoveObserver(Observerobserver){this.subscriberObservers.remove(observer);}publicvoidnotifySubscriberObserver(){for(Observersubscriber:subscriberObservers){subscriber.update();}}}
Enter fullscreen modeExit fullscreen mode

Abstract Subscriber orObserver

packagePatterns.Behavioral.observer;publicabstractclassObserver{publicStringsubscriberName;publicYouTubeChannelSubjectsubject;publicObserver(YouTubeChannelSubjectyouTubeChannelSubject,Stringname){this.subject=youTubeChannelSubject;this.subscriberName=name;}abstractvoidupdate();publicYouTubeChannelSubjectgetSubject(){returnthis.subject;}}
Enter fullscreen modeExit fullscreen mode

Concrete Subscribers

packagePatterns.Behavioral.observer;publicclassSubscriberOneObserverextendsObserver{publicSubscriberOneObserver(YouTubeChannelSubjectsubject,Stringname){super(subject,name);// add this subscriber as of the observers of the youtube channel defined by object 'subject'this.subject.addObserver(this);}@Overridevoidupdate(){System.out.println(this.subscriberName+" got updated !");System.out.println(this.subject.getChannelName()+" has updated contents, the total content on the channel now is "+this.subject.getContents().size());System.out.println("List of contents on the channel "+this.subject.getChannelName()+" are  as follows: ");for(Stringcontent:subject.getContents()){System.out.println(content);}System.out.println("------------------------------");}}
Enter fullscreen modeExit fullscreen mode
packagePatterns.Behavioral.observer;publicclassSubscriberTwoObserverextendsObserver{publicSubscriberTwoObserver(YouTubeChannelSubjectsubject,Stringname){super(subject,name);// add this subscriber as of the observers of the youtube channel defined by object 'subject'this.subject.addObserver(this);}@Overridevoidupdate(){System.out.println(this.subscriberName+" got updated !");System.out.println(this.subject.getChannelName()+" has updated contents, the total content on the channel now is "+this.subject.getContents().size());System.out.println("List of contents on the channel "+this.subject.getChannelName()+" are  as follows: ");for(Stringcontent:subject.getContents()){System.out.println(content);}System.out.println("------------------------------");}}
Enter fullscreen modeExit fullscreen mode

Main

packagePatterns.Behavioral.observer;publicclassMain{publicstaticvoidmain(Stringargs[]){//creating youtube channelYouTubeChannelSubjectsubject=newYouTubeChannelSubject();//subscriber's of the above youtube channelnewSubscriberOneObserver(subject,"prashant");newSubscriberTwoObserver(subject,"sandeep");//now updating the contents of the youtube channelsubject.addNewContent("Men Vs Women survive the wilderness of $500,000");subject.addNewContent("7 Days stranded in a cave");}}
Enter fullscreen modeExit fullscreen mode

output

prashant got updated !Mr.Beast has updated contents, the total content on the channel now is 1List of contents on the channel Mr.Beast are  as follows: Men Vs Women survive the wilderness of $500,000------------------------------sandeep got updated !Mr.Beast has updated contents, the total content on the channel now is 1List of contents on the channel Mr.Beast are  as follows: Men Vs Women survive the wilderness of $500,000------------------------------prashant got updated !Mr.Beast has updated contents, the total content on the channel now is 2List of contents on the channel Mr.Beast are  as follows: Men Vs Women survive the wilderness of $500,0007 Days stranded in a cave------------------------------sandeep got updated !Mr.Beast has updated contents, the total content on the channel now is 2List of contents on the channel Mr.Beast are  as follows: Men Vs Women survive the wilderness of $500,0007 Days stranded in a cave------------------------------prashantmishra@Prashants-MacBook-Air machinecoding %
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

There is always a price for those who persevere.
  • Location
    India
  • Education
    Computer Science
  • Work
    Software Engineer @JPMorganChase&Co.
  • Joined

More fromPrashant Mishra

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp