Java Common Design Patterns 16: Observer patterns for common design patterns (behavioral patterns)

Source: Internet
Author: User

1. Java Viewer mode (Observerpattern)

(1) Overview:

We use news apps in our lives, and when we are interested in a particular column, we tend to subscribe to this column of news, such as my interest in the military bar, I will subscribe to the military Bar news. In this case, once the military column news updates, the app will automatically pop up notifications to let us know.

This is the observer pattern, she defines a one-to-many dependency between objects, and when the state of an object (the observer) changes, all objects that depend on it (the observer) are notified and automatically updated.

(2) The UML class diagram of the Observer pattern:

Role Description:

1)Subject: Abstract subject, that is, the role of the Observer (Observable) , the abstract subject character holds references to all observer objects in a set , Each topic can have any number of observers, and abstract topics provide an interface that can add and remove observer objects.

2)ConcreteSubject: A specific theme, the role of the relevant State into the specific observer object, in the context of the specific topic changes in time , to all registered observers to give notice , the specific theme role is called The specific observed (concrete Observable) role .

3)Observer: Abstract Observer, the role is an abstract class of observers , which defines an updated interface that updates itself when the subject changes are notified .

4)Concreteobserver: The specific observer , which implements an updated interface for the abstract observer role definition, to update its own state when the state of the theme changes .

2. Observer Pattern Code implementation:

(1) Here is a typical example of a headhunter. The figure has 2 characters-headhunters and job seekers. Job seekers are registered with the Headhunter and the headhunter notifies the job seeker when there is a new job opportunity.

Observer mode-a UML diagram of headhunters and job Seekers , as follows:

(2) Create a new Java project as follows:

Subject (interface): Abstract subject, viewer role .

1  Packagecom.himi.observable;2 3 ImportCom.himi.observer.Observer;4 5  Public InterfaceSubject {6      Public voidregisterobserver (Observer o);7 8      Public voidremoveobserver (Observer o);9 Ten      Public voidnotifyallobservers (); One}

Headhunter: The specific subject, the role of the person who is the Observer .

1  Packagecom.himi.observable;2 3 Importjava.util.ArrayList;4 5 ImportCom.himi.observer.Observer;6 7  Public classHeadhunterImplementsSubject {8 9     //define a list of users, such as Mike, Bill, etc.Ten     PrivateArraylist<observer>userlist; One     PrivateArraylist<string>jobs; A   -      PublicHeadhunter () { -UserList =NewArraylist<observer>(); theJobs =NewArraylist<string>(); -     } -   - @Override +      Public voidregisterobserver (Observer o) { - Userlist.add (o); +     } A   at @Override -      Public voidremoveobserver (Observer o) {} -   - @Override -      Public voidnotifyallobservers () { -          for(Observer o:userlist) { inO.update ( This); -         } to     } +   -      Public voidaddjob (String job) { the          This. Jobs.add (Job); * notifyallobservers (); $     }Panax Notoginseng   -      PublicArraylist<string>getjobs () { the         returnjobs; +     } A   the      PublicString toString () { +         returnjobs.tostring (); -     } $  $}

Observer (interface): an abstract class of abstract observers, observers.

1  Package Com.himi.observer; 2 3 Import Com.himi.observable.Subject; 4 5  Public Interface Observer {6      Public void Update (Subject s); 7 }

Jobseeker: the specific observer .

1  PackageCom.himi.observer;2 3 ImportCom.himi.observable.Subject;4 5  Public classJobseekerImplementsObserver {6 7     PrivateString name;8      9      PublicJobseeker (String name) {Ten          This. Name =name; One     } A @Override -      Public voidUpdate (Subject s) { -System.out.println ( This. Name + "Got notified!"); the         //Print job list - System.out.println (s); -     } -  +}

Finally, let's test the Observer Pattern code as follows:

1  Packagecom.himi.test;2 3 ImportCom.himi.observable.HeadHunter;4 ImportCom.himi.observer.JobSeeker;5 6  Public classTest {7 8      Public Static voidMain (string[] args) {9Headhunter hh =Newheadhunter ();TenHh.registerobserver (NewJobseeker ("Mike")); OneHh.registerobserver (NewJobseeker ("Chris")); AHh.registerobserver (NewJobseeker ("Jeff")); -   -         //each time you add a job, all the job-seeking people can be notified.  theHh.addjob ("Baidu Job"); -Hh.addjob ("Alibaba Job"); -Hh.addjob ("Tecent Job"); -     } +  -}

Run the program as follows:

Java Common Design Patterns 16: Observer patterns for common design patterns (behavioral patterns)

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.