Understanding Java event handling mechanism from scratch (2)

Source: Internet
Author: User
Tags event listener

The example in the first section is too simplistic to understand the Java event handling mechanism (1) from scratch, simply to make the code seem useless. But no way, we continue to write this useless code, and then lead to the next phase of really useful code.

One: The event-driven model first glimpse

We're going to say that the event-driven model is an upgraded version of the Observer pattern, so let's talk about the corresponding relationship:

Viewer for Listener (student)

The observer corresponds to the event source (teacher)

Event sources generate events and listeners listen for events. Love a dead-end friend may say, I rub, what is to generate events, listen to events, event events exactly what?

Don't panic, if we use code to do things, the event source is a class, and the event is the line of business code in the event source. This involves a total of four classes, the event source (i.e., the teacher, the observer), the event, the listener interface, and the specific listener (i.e., the student, the observer).

As we mentioned in the first section of our last article, there is certainly a ready-made event model class in the JDK, so let's take a look at one.

First of all, look at the listener (that is, the students, that is, the observer, you do not bother me, keep dropping parentheses to remind, this is to keep giving you a deeper impression),

Package java.util;

/**
* A tagging interface that all event listener interfaces must extend.
* @since JDK1.1
*/
Public interface EventListener {
}

Simple enough to be no more simple, right, even a declaration of the method is not, then what is the meaning of its existence? Remember the object-oriented model, so its meaning is to tell all callers that I am a listener.

Then take a look at the source of the event (i.e., the teacher, the observer),

Package java.util;

/**
* <p>
* The root class from which all event state objects shall is derived.
* <p>
* All Events is constructed with a reference to the object, the "source",
* That's logically deemed to being the object upon which the Event in question
* initially occurred upon.
*
* @since JDK1.1
*/

public class EventObject implements Java.io.Serializable {

Private static final long serialversionuid = 5516075349620653480L;

/**
* The object on which the Event initially occurred.
*/
protected transient Object source;

/**
* Constructs a prototypical Event.
*
* @param source the object on which the Event initially occurred.
* @exception illegalargumentexception if source is null.
*/
Public EventObject (Object source) {
if (Source = = null)
throw new IllegalArgumentException ("null source");

This.source = source;
}

/**
* The object on which the Event initially occurred.
*
* @return the object on which the Event initially occurred.
*/
Public Object GetSource () {
return source;
}

/**
* Returns a String representation of this eventobject.
*
* @return A a String representation of this eventobject.
*/
Public String toString () {
Return GetClass (). GetName () + "[source=" + source + "]";
}
}

This class is also very simple, if the observer pattern in the upper class and the results have a lot of logic, then the event-driven model of the upper class and interface simply can not see anything. That's right

In the event-driven model, the JDK designers performed the most advanced abstraction, which was to make the upper class just represent: I am an event source, or I am a listener!

II: Teacher assignment of the event-driven model version

The usual, let's first give the class diagram:

The code then implements the following:

Viewer interface (student). Because in the event-driven model, there is only one interface without any method, EventListener, so we can implement one of our own interfaces first. To keep up with the previous code, the name of the method we declared in the interface is also called update. Note that we can of course not take that name, and even add other methods to the statement, looking at our business needs.

Package com.zuikc.events;

Import java.util.Observable;

Public interface Homeworklistener extends Java.util.EventListener {

public void update (Homeworkeventobject o, Object Arg);
}

Then implement the Observer Class (student) as follows:

Package com.zuikc.events;

public class Student implements homeworklistener{
private String name;
Public Student (String name) {
THIS.name = name;
}
@Override
public void update (Homeworkeventobject o, Object Arg) {
Teacher Teacher = O.getteacher ();
System.out.printf ("Student%s" observed (actually notified)%s was assigned the job "%s" \ n ", THIS.name, Teacher.getname (), ARG);
}

}

Compare the previous article, have you changed?

The event source is then implemented in this class, as follows:

Package com.zuikc.events;

public class Homeworkeventobject extends Java.util.EventObject {

Public Homeworkeventobject (Object source) {
Super (source);
}
Public Homeworkeventobject (Teacher Teacher) {
Super (teacher);
}
Public Teacher Getteacher () {
Return (Teacher) Super.getsource ();
}

}

In this class, the focus is on the Getteacher method, which encapsulates the GetSource method of the parent class EventObject. Theoretically, we can use the GetSource method of the parent class as well, but it is more readable to encapsulate it again in subclasses.

And then there is our teacher class, as follows:

Package com.zuikc.events;

Import java.util.*;

public class Teacher {
private String name;
Private list<string> Homeworks;
/*
* Teacher class to maintain a list of their own listeners (students), why?
* In the Observer mode, the teacher is the observer, inheriting from the java.util.observable,observable included in this list
* Now we don't have this list, so create a
*/
Private set

Public String GetName () {
return this.name;
}

Public Teacher (String name) {
THIS.name = name;
This.homeworks = new arraylist<string> ();
This.homeworklistenerlist = new hashset}

    public void sethomework (String homework) {
        System.out.printf ("%s was assigned job%s \ n", this.name, homework);
        Homeworks.add (homework);
        Homeworkeventobject event = new Homeworkeventobject (this);
       /*
         * in observer mode, We call observable's notifyobservers directly to notify the Observer
         * Now we can only notify ourselves ~ ~
         */
        for ( Homeworklistener listener:homeworklistenerlist) {
             Listener.update (event, homework);
       }

}
public void Addobserver (Homeworklistener homeworklistener) {
Homeworklistenerlist.add (Homeworklistener);
}

}

This class is a little bit longer, and there are several places to note:

In the first place, teacher has no parent class, and teacher is encapsulated in Homeworkeventobject as the source of the event. There's nothing wrong with the business object and the framework code isolated and decoupled very well, but because of this, we need to maintain a student list in teacher, so we see the homeworklistenerlist variable.

Second, in the observer pattern, we call observable's notifyobservers directly to notify the observer, and now we're on our own, so we see this code,

for (Homeworklistener listener:homeworklistenerlist) {
Listener.update (event, homework);
}

This is not a problem, let's continue to look at the client code:

Package com.zuikc.events;

Import Java.util.EventListener;

public class Client {

public static void Main (string[] args) {
Student student1= New Student ("Zhang San");
Student Student2 = new Student ("John Doe");
Teacher teacher1 = new Teacher ("ZUIKC");
Teacher1.addobserver (STUDENT1);
Teacher1.addobserver (Student2);
Teacher1.sethomework ("event mechanism the second day of Operation");
}

}

The results are as follows:

From the client's point of view, we almost completely did not change anywhere, with the observer pattern of the client code, but the internal implementation mechanism, we use the event mechanism.

Now let's summarize some of the differences between the observer pattern and the event-driven model:

1: The event source no longer inherits from any schema or the parent of the model itself, completely decoupling the business code;

2: In the event model, each listener (Observer) needs to implement an interface of its own. Yes, look at our mouse events, the table has clicked, double-click, move, and so on events, which is to increase the flexibility of the Code;

Anyway, we've implemented an example of an event-driven model with a bunch of small white code, and while it's not really useful, it explains the principle, and in the next section, we'll look at the slightly more complex and seemingly useful code!

Understanding Java event handling mechanism from scratch (2)

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.