Understanding the viewer pattern of Java design patterns

Source: Internet
Author: User

In the actual life, we often encounter a matter of concern about a thing data changes, such as the life of the temperature recorder, when the temperature changes, we observe its temperature changes in the curve, temperature logging and so on. For this kind of problem, it is close to the "observer pattern" in Java design pattern, it is suitable to solve the program structure problem that many objects keep track of an object data change.

The observer design pattern involves two roles: subject (SUBJECT) and Observer (Observer)

Below is the design pattern code for an existing observer in the Java JDK, showing the use of:

1. Theme (Subject): Observable class derived subclass, only need to define each monitored data and getter (), setter () method, getter method is mainly used for specific observer "pull" data, setter method is mainly used for updating, Set the changed variable and inform the individual observers of the data response. The code is as follows:

Importjava.util.Observable; Public classSubjectextendsobservable{PrivateString data;  PublicString GetData () {returndata; }     Public voidsetData (String data) {//Update Data         This. data =data; //Update Data Flagsetchanged (); //inform the individual observers that there is the role of push dataNotifyobservers (NULL); }}

2. Observer (Observer): Write a specific observer class to implement the Observer interface, passing the subject object with parameters to get the updated data. The update () method is mainly used for "pull" data and process. The code is as follows:

Import java.util.Observable; Import Java.util.Observer;  Public class Implements observer{    @Override    publicvoid  update (Observable o, Object Arg) {         //  TODO auto-generated method stub        Subject Subject = (Subject) o;        System.out.println ("Data is being updated to:" +Subject.getdata ());}            }

Let's write a simple test class to test:

Import Java.util.Observer;  Public class Test {    publicstaticvoid  main (string[] args) {        // TODO auto-generated Method stub        New Observerone ();         New Subject ();        Subject.addobserver (obj);        Subject.setdata ("one");}    }

Output: "Data is being updated to: one"

By the Java JDK implementation of the observer pattern, when the use of the sense of code is very simple, in fact, to see the Observerable Class and observer interface source know that these are expert code, after learning the observer pattern, the following conclusions are drawn:

1) Subject to know which observers are monitoring it, it is stated that there must be a collection class member variable in the subject class, adding and removing and judging whether these observer objects exist.

2) The Observer class must be polymorphic and have a common parent-class interface.

3) The function of the theme is basically fixed, it can be abstracted by adding observer, withdrawing observer, notifying the observer and causing the observer to respond (that is, "pull" the data).

After thinking and summarizing, the following is the custom form of the Observer pattern written:

1. Write the Observer Interface (IOBSERVER). The code is as follows:

 Public Interface iobserver{    // incoming Parameter object can indirectly get the changed subject data public    void  Refresh ( Isubject subject);}

2. Write the topic Interface (Isubject). The code is as follows:

 Public Interface isubject{    // registered observer public    void  Register (iobserver obs);     // revoke observer public    void  unregister (IObserver obs);     // notifies all observers and responds    to data  Public void notifyobservers ();}

3. Add topic abstract class Layer (Abstractsubject). The code is as follows:

Importjava.util.ArrayList; Public classAbstractsubjectImplementsisubject{Privatearraylist<iobserver> array =NewArraylist<iobserver>(); @Override Public voidRegister (IObserver obs) {//TODO auto-generated Method StubArray.add (OBS); } @Override Public voidUnregister (IObserver obs) {//TODO auto-generated Method StubArray.remove (OBS); } @Override Public voidnotifyobservers () {//TODO auto-generated Method Stub         for(intI=0;i<array.size (); i++) {IObserver Obs=Array.get (i); Obs.refresh ( This); }        }}

4. The subject subclass defines the monitored data (Subject). The code is as follows:

 Public class extends abstractsubject{    // the data being monitored is    private  String data        ;  Public String GetData () {        return  data;    }      Public void setData (String data) {        this. data = data;    }} 

5. The Observer object (Observer) "pull" the data to get the data response. The code is as follows:

 Public class Implements iobserver {    @Override    publicvoid  refresh (Isubject obj) {        //  TODO auto-generated method stub        Subject Subject = (Subject) obj;        System.out.println ("Data is being updated to:" +Subject.getdata ());}    }

Finally, write a test class to test:

 Public class Test {    publicstaticvoid  main (string[] args) {        // TODO auto-generated Method stub        New Observer ();         New Subject ();        Subject.register (OBS);        Subject.setdata ("one");        Subject.notifyobservers ();    }}

The output is the same!

Understanding the viewer pattern of Java design patterns

Related Article

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.