Study on the design pattern of JDK Observer

Source: Internet
Author: User
Tags inheritance modifier modifiers

The current design pattern of the introduction of more and more articles, but the design model of the research article is still relatively deficient, which really makes people feel a little regret. The purpose of this paper is to make a concrete analysis of the observer design pattern of JDK in Java (if not specifically, the observer design pattern refers to the implementation of the observer design pattern in Java with JDK).

1.Observer Design Pattern Overview

The observer design pattern belongs to the behavior design pattern in Gof. The implementation of the observer design pattern provided in the JDK consists of the Java.util.Observable class and the Java.util.Observer interface. It is clear from the name that the two roles played in the Observer design pattern: Observer is the observer role, observable is the observed target (subject) role.

Observable is a class that encapsulates subject basic functions, such as registering observer (attach function), logging off observer (Detatch function), and so on. These features are needed for any class that plays the role of Observerable, and it makes sense for the JDK to encapsulate these common functions in a single class. Normally, our class can be called the observerable role class as long as it derives from the Observerable class, and is very simple to use.

2. Difficulties in using observer design patterns

But we have to note that in the actual development of the project, the situation is often much more complicated. Java does not support multiple inheritance features are often a stumbling block to our use of observer design patterns. For example, a class that we design is already a derived class of a class, in which case it would be troublesome to want it to play the observerable role at the same time. How to achieve the effect of "multiple inheritance" is a big problem in front of us. Here we first analyze the observable class.

The principle of the 3.Observable class "trigger notification"

Observable must be "changed" to trigger notification observer this task, which is the essence of its embodiment. See the source code will know one or two. Observerable part of the source code is as follows:

//……省略……
   private boolean changed = false;
   //……省略……
   public void notifyObservers(Object arg) {
   //……省略……
     Object[] arrLocal;
     synchronized (this) {
      //……省略……
      if (!changed)
       return;
       arrLocal = obs.toArray();
       clearChanged();
     }
   //……省略……
   protected synchronized void setChanged() {
    changed = true;
   }

   protected synchronized void clearChanged() {
    changed = false;
   }

As shown in the Bold Italic callout section, in the Notifyobservers (Object Arg) method, the if (!changed) Return statement tells us that if the changed property value is False, it returns directly and does not trigger a notification operation at all. And we notice that the changed property is initialized to false, which means that if we do not actively set the changed property to True, there will be no change, that is to say, no "notification" effect. Therefore, setting the value of the changed property is the key to our application of the JDK observer design pattern. So how do you set the changed property? From the source can be seen, the only entrance is through the setchanged (). Here we analyze the changed properties and the associated methods setchanged () and clearchanged ().

Analysis of the 4.Observable class

The initial value of the Observable#changed property is False, which is easy to understand and is no longer stated in detail. Attentive readers may notice that the two methods associated with the changed property () and clearchanged () are setchanged () and their modifiers are protected. I want to emphasize that it is protected, not public. But does this have its necessity and rationality? The answer is yes. In the previous analysis, I have mentioned that the setchanged () method is a unique portal for setting changed, whose modifiers are defined as protected, which means that it becomes impossible to set the changed property by defining the observable object. In this sense, to apply the observer design pattern, you must inherit the observable class. In this connection, the following is also mentioned. But why not define it as public? This seems hard to understand. Because it is defined as public, can we easily set the value of the changed property? To figure this out, let's take a look at the relevant code in observable:

//……省略……
   public void notifyObservers(Object arg) {
   //……省略……
    for (int i = arrLocal.length-1; i>=0; i--)
     ((Observer)arrLocal[i]).update(this, arg);
   }
    

The meaning of this code is to find all registered observer, and then "notify" each, by calling the Observer#update (Observable,object) method for notification. We see that the first parameter of update is this, and we must also note that this code is the code in the observable class. This is equivalent to the repeated emphasis that "notification" must be observable itself (observable class or its derived class), and not any other class. This means that our observable class is necessary to inherit the observable class, because if you do not inherit it, you will not be able to guarantee a good pass. In other words, using the observable class in a combination way would make little sense. At the same time, the modifier is defined as protected, to ensure that the trigger notification in the obsrvable, will not be notified anywhere else, which appears to be very introverted. If you define the setchanged () modifier as public, you will not be able to guarantee the correct "pass this" requirement, which does not meet the hard requirements of the observable design pattern of "only observalbe can directly or indirectly notify Observer". From this we can see that many of the JDK's philosophy is how strong the ideological.

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.