Design pattern Start--viewer mode

Source: Internet
Author: User

Observer pattern

One, the problem: Define a one-to-many dependency, so that multiple observers listen to a Subject object at the same time, when the subject object changes, will notify all the Observer object

Second, the role: When an object changes need to change other objects at the same time

Third, class diagram

(1) Type of push

(2) Form of pull

Iv. Realization OF

(1) Abstract Theme class

 Public Interface Isubject {    publicvoid  Register (iobserver observer);      Public void Unregister (IObserver observer);      Public void notifyobservers ();}
View Code

(2) Specific subject categories

 Public classSubjectImplementsIsubject {PrivateVector<iobserver> VEC =NewVector<iobserver>(); PrivateString data;  PublicString GetData () {returndata; }     Public voidsetData (String data) { This. data =data; } @Override Public voidregister (IObserver observer) {VEC.ADD (Observer); } @Override Public voidUnregister (IObserver observer) {if(Vec.contains (Observer)) VEC.REMOVE (Observer); } @Override Public voidnotifyobservers () { for(inti = 0; I < vec.size (); i++) {vec.get (i). Refresh ( This); }    }}
View Code

(3) Abstract Viewer class

 Public Interface IObserver {    publicvoid  refresh (isubject subject);}
View Code

(4) Specific observer class

 Public class Implements iobserver {    @Override    publicvoid  refresh (isubject subject) {        = (Subject) Subject;        System.out.println (Sub.getdata ());}    }
View Code

(5) User Class test class

 Public class Client {    publicstaticvoid  main (string[] args) {        new Subject ();         New Observer ();         New Observer ();        Subject.register (one);        Subject.register (both);        Subject.setdata ("Hello World");        Subject.notifyobservers ();    }}
View Code

Design pattern Start--viewer mode

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.