Design Model --- Observer Model

Source: Internet
Author: User

I read the head first design model book yesterday. This book is really good and easy to understand. I was the first time in contact with the design model. I thought it was a very high-end design model. When I was chatting with others, what kind of design model I used? Haha, I am joking. I mainly learn the experience of my predecessors, so that I can make my code design more standardized. Now let's record the first design pattern I learned-The Observer Model.

What is the observer design pattern?

For example, the relationship between newspapers and newspaper subscribers. Once a newspaper has a new newspaper, it will be pushed to its readers. In the observer design mode, the newspaper is the subject, and the reader is the observer. The observer can register or cancel an event with the subject. The subject maintains an observer list. Once the topic changes, the subject is like the observer updating message. This is a simple observer mode.

To achieve this demand: There is a theme of the weather, and many observers will use the data, the current display panel, and the future prediction panel.

Design Concept:

1. Declare a subject interface. A specific topic must be implemented. There are three main methods in it: registerobserver (Observer O), removeobserver (Observer O ), notifyobserver (information info );

2. Declare a weathersubject to implement the subject class, implement various methods in it, and add a Data Structure arraylist to save the observer information.

3. Declare an observer interface. All observers must implement this interface. This interface only has the unique update method for weatherobject update.

4. Declare a currentobserver class. This class implements the observer class and implements the update method.

5. Create a main function, create a weathersubject class, create a currentobserver class, and then simulate weather topic update.

How does the observer communicate with each other after the topic? When declaring a weatherobject class and then declaring a currentobserver class, the constructor transmits the weatherobject instance to the constructor and wants to register it again.

------------------------------------- I am a student, cut ---------------------------------------------------------------------------- thread -------------

The above is the implementation of an observer mode written by myself. In fact, the Java SDK already supports the observer mode. in the utl report, there are two classes: observable and observer. observable corresponds to subject, observer corresponds to observer, and observerable is a class rather than an interface. This violates our best effort to use combinations, it is a bit of a problem to use less inheritance principles. Its usage is a little different from above. You need to call setchange to set the ischange variable to true before notifyobservers takes effect. This is reasonable, because the update speed is too fast for the temperature, and changes very high degrees Celsius, so the observer will receive a lot of information, we hope to push this change only when the change reaches 1 degree, so it can be implemented through setchange.

Another issue that needs to be considered is that some observer may only need some of the attributes of so many messages pushed by subject, so whether these changed messages are pushed or pulled by the observer in the end, this is an issue worth consideration. If the observer uses pull, the getter method must be implemented in the subject, and the changed message does not need to be transmitted in yyobservers, the observer just needs to fetch it.

The collected information may change. Therefore, when the collected information changes, the subject also needs to change, and the observer also needs to change.

  1 #Subject.java  2 class Information  3 {  4     Information(double d,double e,double f)  5     {  6         this.temp = d;  7         this.max = f;  8         this.min = e;  9     } 10     double temp; 11     double min; 12     double max; 13 } 14  15 public interface Subject { 16    void registerObserver(Observer o); 17    void removeObserver(Observer o); 18    void notifyObservers(Information info); 19 } 20 --------------------- 21 WeatherSubject.java 22 import java.util.ArrayList; 23 import java.util.Iterator; 24 import java.util.List; 25  26  27 public class WeatherSubject implements Subject { 28  29     List<Observer> observer; 30     public WeatherSubject() 31     { 32         observer= new ArrayList<Observer>();//programming to interface; 33     } 34     public  void registerObserver(Observer o) 35     { 36         observer.add(o); 37     } 38     public void removeObserver(Observer o) 39     { 40         int index = observer.indexOf(o); 41         if(index!=-1) 42         { 43             observer.remove(index); 44         } 45     } 46     @Override 47     public void notifyObservers(Information info) { 48         // TODO Auto-generated method stub 49         50         Iterator<Observer> iterator = observer.iterator(); 51         for(;iterator.hasNext();) 52         { 53             iterator.next().update(info); 54         } 55     } 56      57     public void changeInfo(double d,double e,double f) 58     { 59         notifyObservers(new Information(d,e,f)); 60     } 61  62 } 63  64 ---------------------------- 65 Observer.java 66  67 public interface Observer { 68     public void update(Information info); 69 } 70  71 ---------------- 72 Display.java  73 public interface Displayable { 74      public void display(); 75 } 76  77 ------------------- 78 CurrentObserver.java 79  80  81 public class CurrentObserver implements Observer,Displayable { 82  83     double temp,max,min; 84     Subject subject; 85     CurrentObserver(Subject subject) 86     { 87         this.subject = subject; //reserver Subject instance for unregister invoke 88         subject.registerObserver(this); 89     } 90     @Override 91     public void update(Information info) { 92         // TODO Auto-generated method stub 93        temp = info.temp; 94        max = info.max; 95        min = info.min; 96        display(); 97     } 98     public void display() 99     {100         System.out.println("Current: "+temp+" "+max+" "+min);101     }102     103 }104 ------------------105 SubjectMain.java106 107 public class SubjectMain {108 109     /**110      * @param args111      */112     public static void main(String[] args) {113         // TODO Auto-generated method stub114        WeatherSubject weather = new WeatherSubject();115        Observer currentObserver = new CurrentObserver(weather);116        weather.changeInfo(13.3, 16.4, 17.9);117     }118 119 }

 

 

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.