Listen to the classic conversations between two members in the Observer mode...

Source: Internet
Author: User

I. Introduction: conversations between two members in observer Mode

<Head first design pattern> in Chapter 2, when talking about the observer mode, there is a classic section. It refers to the conversation between the subject and the observer roles in the Observer mode. The subject is called S, the observer is O (not fully translated by the internal translation ):

S: I'm very glad that in order to improve our relationship, we finally waited for this opportunity to communicate with the observer face to face.

O: Oh, really? I thought you never cared too much about our observers.

S: Well, I always do my best to do my own job, right? Every critical moment, I will tell you what happened... I don't know every one of you. It doesn't mean that I don't care about you. I know the most important thing for you: you have implemented interfaces like observer. Whenever the key point is, I will tell you what happened, and you can handle it right away.

O: Well, it is. But that's just a small part of us. There are many other things you don't know. In any case, I am very familiar with you...

S: Oh, right? What do you know.

O: Okay. For example, when the situation on your side changes, you always transmit the new "intelligence" to each of our observers as soon as possible, in this way, we always know what kind of status you are in. But sometimes this also makes us very upset...

S: Oh, I'm sorry. I have to send my status to my notifier, for example, yyobservers (), and then let it notify you, So you lazy observers will know what happened.

O: OK, and so on. First, we are not lazy, because once you notify us of any changes, we have to deal with many other things between your subject and your notifier. Secondly, why not let us approach you, in this way, we can easily get the aspect that each of us really cares about, and you always push all aspects of things to each of us, some have no effect on me at all.

S: Well... I think that will work more effectively. To tell you this, you observers are observing an employee with more than one thousand fields in XX Company. You want me to tell you after some attributes of those employees have changed, then you said that in this case, I will let you enter my personal world, and then let you get what you want. Do you know which attributes have changed? It is impossible! Maybe the employee's salary has changed, maybe they have changed their boss. In this case, it may be a very dangerous thing! So I cannot let you in my personal world and then let you see what I have.

O: Why don't you leave a public getter method so that we can use this getter method to get what we want?

S: Yes, I can indeed let you pull (pull) to my status. But will it be more convenient to do it as you said just now? If you have to enter my personal world and take what you want, then you may have to call multiple repeated getter methods to get everything you want. That's why I prefer to push something directly to you... Then you can get everything you need directly in the notification tool.

O: Don't be so aggressive! In our observers, there are all kinds of personalities, and you cannot expect everything we need. Let us enter your personal world and get what we need. In this way, if some of our observers only need something like this, we will not be forced to accept everything we give. This is also very convenient for future expansion. Now let's assume that this is the case: for various reasons, if you have grown yourself, you must add a certain State. If you are using the pull method, you do not need to modify the update method of each of our observer, and then add the new thing to go around, you only need to write one more getter Method on yourself to support this new status.

S: Well, I can see that both "Push me" and "pull you" have their own advantages. I have noticed that Java already has built-in support for our observer mode. It allows you to choose whether to push me or pull you.

O: Oh, really? I think I have to feel this benefit...

S: Well, great... I think I should also look at a good example of "pulling you" to change my mindset...

O: What? I did not hear it wrong. Have we reached a consensus? I want to always have it...

(End)

2. Is it "Push me" or "pull you "?

After listening to the classic conversations between the observer mode and the two Members, I think you will be more impressed with the observer mode. Whether it is "Push me" or "pull you", from the above dialogue we can easily conclude that it is entirely dependent on the complexity of the object to be observed, if the object to be observed is more complex, and the observer needs a prompt, so the PUSH model is suitable. If the object to be observed is relatively simple, it is appropriate to pull the model.

Application of the Three-Observer mode in Java programming (focusing on learning the JavaBeans event model)

The process of learning the design pattern has always been like this. Looking at the jdk api or even the source code, you will find that it is more organized and better understood, it can be said that to study the JDK source code (I think other source code is the same), we must have a good understanding of the design pattern. There are two ways to view the details of the observer mode. The first method is to understand the observer and observable classes defined in Java. util. The second method is to study the JavaBeans Component Model for registering event listeners. Before creating the JavaBeans event model, the observer and observable classes describe the implementation of the observer mode. In other words, these classes already exist since Java 1.0. Since these classes are not technically incorrect in design, they have been used for a long time. These classes can also be used to implement the observer mode, but more of them use the JavaBeans event model. I also want to spend more time studying the application in this area, this will be of more help to us in Gui programming.

We prefer to divide the objects in the event processing model: Event objects, event producer objects, and event receiver objects. One object is the producer of the event, the other objects are the receiver of the event, and the event object itself contains information about the event. When the internal status of the event maker changes, an event object representing its status change will be created as needed, and it will be passed to all registered event recipient objects. For this mechanism, I think after listening to the above conversation, we can naturally think that this is based on the observer mode. In fact, we learned from the online information that the event processing mechanism of java1.0 is based on the responsibility chain model (Haha, I didn't learn this design pattern when I wrote this article ~~) Before learning about this event mechanism, let's take a look at the Model-View in MVC. As part of the MVC pattern, they are the relationship between subject and obverser. Therefore, changes to the model must be reflected in the UI object. Swing uses the event model of JavaBeans to implement this notification mechanism. Based on the previous subject and obverserr conversations, there are two implementation methods: one is to notify the event listener that the status has changed, and then the event listener extracts the necessary State information from the model. This mechanism is very effective for components with frequent events. Another method is to send a notification containing changed status information to the UI to the listener. The two methods are different components based on their advantages and disadvantages. For example, the first method is used in jscollbar, and the second method is used in jtable. By the way, if we need to retrieve a batch of data from the database and display it in a large list in the C/S architecture application, a large amount of jtable will be used at this time, then we can better understand this mechanism.

Return to the event listening mechanism. For model, to support multiple views, it does not know each view. It maintains a list of obverser interested in its data. Call addxxxlistener () to add a listener and call the removexxxlistener () method to delete a listener. Both methods require a listener type. All AWT components are subclasses of Java. AWT. component. They all inherit the addxxxlistener () methods from the component class.

For example:

Actionlistener listener = new actionlistener (){

Public void actionreceivmed (actionevent ){

System. Out. println ("the listener receives a notification! ");

}

};

Jbutton button = new jbutton ("Click me! ");

Button. addactionlistener (listener );

In this example, the button includes maintaining a listener aggregation class and providing various methods to manage listener object aggregation, such as addactionlistener, it can be seen that the above listener is a listener object which implements the actionreceivmed method of the actionlistener interface. If you click the button, the actionreceivmed method is triggered, in fact, the actioncommitted med is equivalent to the update () method in the Observer.

Here, we implement a listener interface to attach it to the listener object. The Monitored object is listened on. It is responsible for remembering who is listening. In the JavaBeans component model, the interface for appending and removing observer objects is the add and delete listener naming mode. When the status of the listener object changes, it notifies the observer object. One of the main objectives of this design model is to reduce the coupling between the object and the observer. When a jbutton is selected, instead of calling a specific method called the buttonnotification class, the notification action is abstracted into an interface and can be implemented by any class. Jbutton does not care about the listener to be bound. In fact, the button does not care whether the implementation class is modified. It is concerned that the observer implements this listener.

The following is an excerpt from the Internet:

When using the observer mode, you need to pay attention to many complicated problems. First, memory leakage may occur. The Monitored object maintains the reference of an observer. The Spam collector cannot delete the observer before the listener object releases this reference. You must be aware of this possibility and delete the observer when appropriate. Note that the observer object is maintained in an unordered set. At least this is the case when the listener is registered. You do not need to know whether the first registered listener is called first or later. If you need an ordered call, for example, a must be called first and then B. Then you must introduce an intermediate layer object to force this order. Simply registering listeners in order cannot ensure the call order.

Iv. Summary

The observer pattern is widely used in the design pattern. I hope this article can help you learn the observer pattern.

 

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.