Home > Java > javaTutorial > Understand the JAVA event handling mechanism from scratch

Understand the JAVA event handling mechanism from scratch

巴扎黑
Release: 2017-06-23 16:37:25
Original
1212 people have browsed it

The word "event" has been overused. Precisely because of the misuse of "events", many people do not understand clearly when using events, but follow the same example. As a result, after studying and working for many years, they still do not know what an event processor is and what an event holder is. So, if you are still afraid of the word Event, then this article is exactly what you need. Let us explain the java event processing mechanism step by step from easy to difficult, from concrete to abstract.

1: Observer Pattern

To understand events and monitoring, we must first understand the observer pattern.

What is the observer mode? Let’s first look at a familiar scene:

1: The teacher assigns homework, notifies students;

#2: The students observed that the teacher assigned homework and started to do it;

First of all, let me make it clear that I have always been very opposed to using cats and dogs as teachers. Students use this scenario to explain coding issues, so the topic will definitely return to actual code at the end. Closer to home, in this scene, the students are the observers and the teachers are the observed, but everyone must pay attention:

As the observed, the teacher actually takes the initiative and is interested in I bolded the word "notification" in the article because it seems to be a simple notification, but in fact it requires a lot of things (writing a lot of code).

Okay, let’s implement the above scenario first:

Understand the JAVA event handling mechanism from scratch

Code:

Observer, student

package com.zuikc.events;

import java.util.Observable;

public class Student implements java.util.Observer {

private String name;
public Student(String name){
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
Teacher teacher = (Teacher) o;
System.out.printf("Student %s observed (actually was notified) that %s assigned homework "%s" \n", this.name, teacher.getName(), arg );
}

}

Observer, teacher

package com.zuikc.events;

import java.util.*;

public class Teacher extends java.util.Observable {

private String name;
private List homeworks;

public String getName () {
Return This.name;
}

Public Teacher (String name) {
This.Name = Name; ing & gt; () ;
}

public void setHomework(String homework) {

System.out.printf("%s assigned homework %s \n", this.name, homework);
homeworks.add(homework);
setChanged();
notifyObservers(homework);

}

}


# #Client:

package com.zuikc.events;

public class Client {

public static void main(String[] args) {

Student student1= new Student("Zhang San");

Student student2 = new Student("李思");
Teacher teacher1 = new Teacher("zuikc");
teacher1.addObserver(student1) ;
      teacher1.addObserver(student2);
      teacher1.setHomework("Event mechanism first day homework");
}

}

Many beginners Scholars have an illusion that the action of "observation" is active, so they think that in code implementation, Reader actively calls its own update. Unfortunately, of course not, in code implementation, update is the "observed" Called actively by Teacher. Some people say that I only saw

setChanged();
notifyObservers(homework);


in Teacher and I didn’t see it calling update, so please Check its parent class Observable, in the notifyObservers method,

for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal [i]).update(this, arg);

Look at the results:

Understand the JAVA event handling mechanism from scratch

Note that in the above code, I directly used the class Observable and the interface Observer in the java.util package. Of course, we You can also write these two things yourself.

2: Basic Observer Mode

Beginners are not used to using the api in java.util right from the beginning, and may find it difficult to If you can’t touch it, then we will write a basic version of the observer pattern ourselves. Everyone can feel it. During the writing process, be sure to compare the UML diagram and code in the previous section, and then think silently: There is no difference between them. no difference!

Above picture:

Understand the JAVA event handling mechanism from scratch

Above code:

Observer, interface

package com.zuikc ;

public interface Observer {

void update(Observable o);
}

For specific observers, I wrote two:

class ConcreteObserver1 implements Observer {

public void update(Observable o) {
System.out.println("Observer 1 observed" + o.getClass().getSimpleName( ) + "Change occurred");
System.out.println("Observer 1 responded");
}
}

class ConcreteObserver2 implements Observer {

public void update(Observable o) {
System.out.println("Observer 2 observed" + o.getClass().getSimpleName() + "Changed");
System.out. println("Observer 2 responded");
}
}

Observer

package com.zuikc;

import java.util.ArrayList;
import java.util.List;

public class Observable {

List observers = new ArrayList();

public void addObserver(Observer o) {
observers.add(o);
}

public void doSomething() {
System.out.println("I am Observed, I changed ");
// Actively notify all observers
NotifyobServers ();
}

## Public void NotifyobServers () {

for (Observer observer : observers) {
          observer.update(this);
    }
  }
}

Client:

package com.zuikc;

public class Client {

public static void main(String[] args) {

Observable observable = new Observable();
observable.addObserver( new ConcreteObserver1());
observable.addObserver(new ConcreteObserver2());
observable.doSomething();
}

}

Everyone can Run the code yourself and see what happens.

In the above code, we created an interface and an observer class. Although it is a bit simpler, it achieves the effect of demonstration. Of course, we can also copy the source code in the JDK intact as the code for our two files.

If you are already quite familiar with the above code, you can also study the update method. In the first section, we brought the arg parameter, but it is not included in this basic version. It doesn't matter, you can bring it with you if you want, or you can bring it with you if you don't want to. Code is freedom, as long as you realize the function.

3: The purpose of the observer pattern

The basic version of the observer pattern is too simple after all. In the code in our first section , we can summarize:

1: The teacher class has nothing to do with the student class. He only relies on the observer interface. If one day, his homework is not only assigned to students, but as an excellent lecturer, he also sends it to the entire school. The teacher is used as a reference, then as long as the teacher class also implements the observer interface, we can also add the teacher to the teacher's observer list;

2: The observer pattern separates the observer and the observed Responsibility for each class, allowing each class to maintain its own functions, improves the reusability of the system;

3: Observation seems to be an active behavior, but in fact the observer does not actively call his own business code. On the contrary, it is called by the observer. Therefore, the observer pattern has another name, called publish-subscribe pattern. I think the latter is more appropriate;

The observer pattern has another form, which is event-driven Model, these two methods are very close in terms of implementation mechanism. On the basis of understanding the observer pattern, it is very simple to understand event drive.

The above is the detailed content of Understand the JAVA event handling mechanism from scratch. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template