Java Design Pattern observation (Observer pattern)

Source: Internet
Author: User
Tags class definition event listener

Observer pattern Design patterns are typically used for. This is an event listener model.

The model has two functions, one is subject, and the other is a observer. Subject saves multiple observer references once a particular event occurs. Subject it will notify all observer. Observer run the associated program logic after getting the notification.

Among them, observer only had the ability to be subject known before subject. It's like a newspaper, and only if we make a subscribe application to the publishers will the publishers put us on the list of subscribers. Then every time a new newspaper is printed, the Publisher Society informs subscribers to fetch the newspaper. The subscriber here is Observer, the publishing house is Subject.


Subject, the class diagram for observer such as the following:



Here's an example of the observer pattern.

When companies need to recruit talent. Tend to look for headhunters (headhunter). Headhunters know a lot about how many job seekers (applicant) are contacted. Once a company is hiring. Headhunters will call the job seekers to get their jobs done by them.

In this area, headhunting is Subject, job seekers are Observer.

Let's implement such a feature.

Design two classes, headhunter and applicant. They represent headhunters and job seekers respectively.

The Headhunter class has an attribute jobName. When JobName has a new value (the equivalent of hiring a company). Headhunter told all the applicant he knew that he had a job.

Class diagrams such as the following:



Subject Interface Definition:

public interface Subject {void Registerobjserver (Observer ob); void Removeobserver (Observer ob); void Notifyobservers ();}

Observer Interface Definition:

public interface Observer {void update (Subject Subject);}

Headhunting class Definition:

public class Headhunter implements Subject {private list<observer> oblist = new arraylist<observer> (); Private Boolean isnotify = True;private String jobname;/** * REGISTER a observer */@Overridepublic void Registerobjserver (Observ Er ob) {oblist.add (OB);} /** * Remove a Observer */@Overridepublic void Removeobserver (Observer ob) {oblist.remove (OB);} /** * NOTIFY all observer */@Overridepublic void Notifyobservers () {if (true = = Isnotify) {performnotify (); isnotify = false;}} /** * Join a new job.

Immediately notify all Observer * @param jobName */public void Setjobname (String jobName) {this.jobname = Jobname;isnotify = True;noti Fyobservers ();} private void Performnotify () {for (Observer ob:oblist) {ob.update (this);}} Public String Getjobname () {return jobName;}}


Job Seeker class Definition:

public class Applicant implements Observer {private String name;public applicant (String name) {this.name = name;} @Overridepublic void Update (Subject Subject) {Headhunter H = (headhunter) subject;out.println (name + "received notification:" + H.getjobnam E ());}}


The function of this applet is that once Headhunter's Setjobname () method is called (that is, there is a new job), Headhunter immediately notifies it that the applicant tells them to have a job. The program test code such as the following:

public static void Main (string[] args) {headhunter hh = new Headhunter ();//register Observerhh.registerobjserver (New applicant ( "Zhang San"), Hh.registerobjserver (New Applicant ("John Doe")), Hh.registerobjserver (New Applicant ("Harry"));//Join a job// At this point all Observer's update () methods will be called Hh.setjobname ("Java program Ape");}



Execution Result:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbmvvc21pdgg=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">


Observer Pattern is widely used in swing, such as calling JButton's AddListener () to join an event listener. At this time JButton is Subject, Listener is Observer.

Because the observer pattern is more frequently used, we need to grasp the experience.

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Java Design Pattern observation (Observer pattern)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.