Java and C # event processing mechanism (zt)

Source: Internet
Author: User

Both Java and C # implement the event source-event responder mechanism, but not exactly the same. Java implements two-level entity object Methods: Event source and event responder. The event responder here is also the event listener, C # implements a three-level object method for event source-proxy-event responder. The two methods are described below.

Java event processing

In terms of concept, an event is a transmission mechanism in which a certain state changes between the "source object" and "listener object. Things have many different purposes, such as mouse events, window boundary change events, and keyboard events that are often handled in Windows systems. In Java, a general and extensible event mechanism is defined. This mechanism can:

· Provides a public framework for defining and expanding event types and transfer models, and is suitable for a wide range of applications.

· High Integration with the Java language and environment.

· Events can be captured and triggered by the descriptive environment.

· Enable other construction tools to take some technology to directly control events during design, as well as the connections between the event source and event listener.

· The event mechanism itself does not rely on complex development tools.

· The transfer of an event from the event source to the listener is performed by calling the Java method of the target listener object. A specific Java method is defined for the occurrence of each specific event. These methods are centrally defined in the event listener interface, which inherits java. util. eventlistener. The class that implements some or all of the methods of the event listener interface is the event listener. With the occurrence of an event, the corresponding State is usually encapsulated in the event state object, which must inherit from Java. util. eventobject. The event status object is passed as a single parameter to the listener method responding to the event. The identifier of the event source that generates a specific event is: follow the prescribed design format to define the registration method for the event listener and accept references to the instance of the specified event listener interface.

Sometimes, when the event listener cannot directly implement the event listener interface, or there are other additional actions, it is necessary to insert an event adapter class instance between one source and one or more listeners, to establish the relationship between them.

Event State object)

State information related to event occurrence is generally encapsulated in an event state object, which is a subclass of Java. util. eventobject. According to design habits, the name of this event state object class should end with event. For example:

      
       
Public class mousemovedexampleevent extends java. util. eventobject

       
{Protected int X, Y;
/* Create a mouse movement event mousemovedexampleevent */
Mousemovedexampleevent (Java. AWT. component source, Point Location ){
Super (source );
X = location. X;
Y = location. Y;
}
/* Get the mouse position */
Public point getlocation (){
Return new point (x, y );
}}

Eventlistener interface and event listener

Because the Java event model is called based on methods, a method to define and organize event manipulation methods is required. All event manipulation methods are defined in the eventlistener interface that inherits the java. util. eventlistener class. according to regulations, the name of the eventlistener interface should end with the listener. Any class that wants to manipulate the methods defined in the eventlistener interface must implement this interface. This class is the event listener. For example:

      
       
/* First defines a mouse movement event object */

       
Public class mousemovedexampleevent extends java. util. eventobject {
// This class contains the status information related to the mouse movement event
...
}
/* Defines the listener interface for mouse movement events */
Interface mousemovedexamplelistener extends java. util. eventlistener {
/* This interface defines the methods supported by the mouse movement event listener */
Void mousemoved (mousemovedexampleevent Mme );
}

      
       
Class arbitraryobject implements mousemovedexamplelistener {

       
Public void mousemoved (mousemovedexampleevent Mme)
{...}
}

Arbitraryobject is the listener of the mousemovedexampleevent event.

Registration and cancellation of event monitors

To register an event listener to an appropriate event source and establish an event stream between the source and event listener, the event source must provide the event listener with registration and cancellation methods. This usage process has been seen in the previous bound attribute introduction. In practice, the registration and cancellation of Event Listeners should use the standard design format:

      
       
Public void add <listenertype> (<listenertype> listener );

       
Public void remove <listenertype> (<listenertype> listener );

For example, you first define an event listener interface:

      
       
Public interface modelchangedlistener extends java. util. eventlistener {

       
Void modelchanged (eventobject E );
}

Then define the event source class:

      
       
Public abstract class model {
       
Private vector listeners = new vector (); // defines an array for storing Event Listeners
/* <Listenertype> in the above design format is the following modelchangedlistener */
Public synchronized void addmodelchangedlistener (modelchangedlistener MCL)
{Listeners. addelement (MCL);} // register the listener into the listeners array.
Public synchronized void removemodelchangedlistener (modelchangedlistener MCL)
{Listeners. removeelement (MCL); // deregister the listener from listeners
}
/* The preceding two methods are named synchronized, because several objects may be executed simultaneously when running in a multi-threaded environment.
The registration and logout operations use synchronized to ensure synchronization between them. Development tools or Program Personnel use these two methods to establish the source and Supervision
Event streams between listeners */
Protected void policymodelchanged ()
{/** The event source uses this method to notify the listener of A modelchanged event */
Vector L;
Eventobject E = new eventobject (this );
/* First copy the listener to the L Array and freeze the eventlisteners status to pass events. This ensures that
The corresponding method of the target listener who has received the event does not take effect until it is passed to all listeners. */
Synchronized (this ){
L = (vector) listeners. Clone ();
}
For (INT I = 0; I <L. Size (); I ++ ){
/* Notify each listener registered in the listener queue in sequence that the modelchanged event occurs,
The event status object e is passed as a parameter to each listener in the listener queue */
(Modelchangedlistener) L. elementat (I). modelchanged (E );
}
}
}

In the program, we can see that the event source model class explicitly calls the modelchanged method in the interface. Actually, the event state Object E is used as a parameter and passed to the modelchanged method in the listener class.

Both Java and C # implement the event source-event responder mechanism, but not exactly the same. Java implements two-level entity object Methods: Event source and event responder. The event responder here is also the event listener, C # implements a three-level object method for event source-proxy-event responder. The two methods are described below.

Java event processing

In terms of concept, an event is a transmission mechanism in which a certain state changes between the "source object" and "listener object. Things have many different purposes, such as mouse events, window boundary change events, and keyboard events that are often handled in Windows systems. In Java, a general and extensible event mechanism is defined. This mechanism can:

· Provides a public framework for defining and expanding event types and transfer models, and is suitable for a wide range of applications.

· High Integration with the Java language and environment.

· Events can be captured and triggered by the descriptive environment.

· Enable other construction tools to take some technology to directly control events during design, as well as the connections between the event source and event listener.

· The event mechanism itself does not rely on complex development tools.

· The transfer of an event from the event source to the listener is performed by calling the Java method of the target listener object. A specific Java method is defined for the occurrence of each specific event. These methods are centrally defined in the event listener interface, which inherits java. util. eventlistener. The class that implements some or all of the methods of the event listener interface is the event listener. With the occurrence of an event, the corresponding State is usually encapsulated in the event state object, which must inherit from Java. util. eventobject. The event status object is passed as a single parameter to the listener method responding to the event. The identifier of the event source that generates a specific event is: follow the prescribed design format to define the registration method for the event listener and accept references to the instance of the specified event listener interface.

Sometimes, when the event listener cannot directly implement the event listener interface, or there are other additional actions, it is necessary to insert an event adapter class instance between one source and one or more listeners, to establish the relationship between them.

Event State object)

State information related to event occurrence is generally encapsulated in an event state object, which is a subclass of Java. util. eventobject. According to design habits, the name of this event state object class should end with event. For example:

      
       
Public class mousemovedexampleevent extends java. util. eventobject

       
{Protected int X, Y;
/* Create a mouse movement event mousemovedexampleevent */
Mousemovedexampleevent (Java. AWT. component source, Point Location ){
Super (source );
X = location. X;
Y = location. Y;
}
/* Get the mouse position */
Public point getlocation (){
Return new point (x, y );
}}

Eventlistener interface and event listener

Because the Java event model is called based on methods, a method to define and organize event manipulation methods is required. All event manipulation methods are defined in the eventlistener interface that inherits the java. util. eventlistener class. according to regulations, the name of the eventlistener interface should end with the listener. Any class that wants to manipulate the methods defined in the eventlistener interface must implement this interface. This class is the event listener. For example:

      
       
/* First defines a mouse movement event object */

       
Public class mousemovedexampleevent extends java. util. eventobject {
// This class contains the status information related to the mouse movement event
...
}
/* Defines the listener interface for mouse movement events */
Interface mousemovedexamplelistener extends java. util. eventlistener {
/* This interface defines the methods supported by the mouse movement event listener */
Void mousemoved (mousemovedexampleevent Mme );
}

      
       
Class arbitraryobject implements mousemovedexamplelistener {

       
Public void mousemoved (mousemovedexampleevent Mme)
{...}
}

Arbitraryobject is the listener of the mousemovedexampleevent event.

Registration and cancellation of event monitors

To register an event listener to an appropriate event source and establish an event stream between the source and event listener, the event source must provide the event listener with registration and cancellation methods. This usage process has been seen in the previous bound attribute introduction. In practice, the registration and cancellation of Event Listeners should use the standard design format:

      
       
Public void add <listenertype> (<listenertype> listener );

       
Public void remove <listenertype> (<listenertype> listener );

For example, you first define an event listener interface:

      
       
Public interface modelchangedlistener extends java. util. eventlistener {

       
Void modelchanged (eventobject E );
}

Then define the event source class:

      
       
Public abstract class model {
       
Private vector listeners = new vector (); // defines an array for storing Event Listeners
/* <Listenertype> in the above design format is the following modelchangedlistener */
Public synchronized void addmodelchangedlistener (modelchangedlistener MCL)
{Listeners. addelement (MCL);} // register the listener into the listeners array.
Public synchronized void removemodelchangedlistener (modelchangedlistener MCL)
{Listeners. removeelement (MCL); // deregister the listener from listeners
}
/* The preceding two methods are named synchronized, because several objects may be executed simultaneously when running in a multi-threaded environment.
The registration and logout operations use synchronized to ensure synchronization between them. Development tools or programmers use these two methods to establish source and Supervision
Event streams between listeners */
Protected void policymodelchanged ()
{/** The event source uses this method to notify the listener of A modelchanged event */
Vector L;
Eventobject E = new eventobject (this );
/* First copy the listener to the L Array and freeze the eventlisteners status to pass events. This ensures that
The corresponding method of the target listener who has received the event does not take effect until it is passed to all listeners. */
Synchronized (this ){
L = (vector) listeners. Clone ();
}
For (INT I = 0; I <L. Size (); I ++ ){
/* Notify each listener registered in the listener queue in sequence that the modelchanged event occurs,
The event status object e is passed as a parameter to each listener in the listener queue */
(Modelchangedlistener) L. elementat (I). modelchanged (E );
}
}
}

In the program, we can see that the event source model class explicitly calls the modelchanged method in the interface. Actually, the event state Object E is used as a parameter and passed to the modelchanged method in the listener class.

Adaption class

Adaptation classes are an extremely important part of the Java event model. In some applications, events are transmitted from the source to the listener through the Adaptation class ". For example, when the event SOURCE sends an event, and several event listening objects can receive the event, but only the specified object responds to the event, you need to insert an event adapter class between the event source and the event listener to specify which listeners should respond to the event. The adaptation class becomes the event listener. The event source actually registers the adaptation class as the listener into the listener queue, but the real event responder is not in the listener queue, the action that the event responder should do is determined by the adaptation class. Currently, most development tools are generatingCodeEvent processing is performed by the adaptation class.

C # event processing

In. NET application development, whether it is web forms (Asp. net) or Windows Forms, all involve the Event Response and processing of a large number of objects, such as the customer submitting an order online, or moving the mouse over the windows window. In C #, how does one declare an event and add a response method to the event?

In C #, the events member is used to declare a class event. The following syntax is used to declare an event member in a class:

      
       
Public event indicates the name of the event.

      

For example, if a click event member is declared in the control class, its syntax is as follows:

      
       
Public event eventhandler click;

      

In C #, a new data type delegate (representative) is added to solve the event processing problem. The data type is very similar to the pointer in C language. What is different from the pointer is that the Code is secure and manageable. Due to the simplicity of C # itself, it is very easy to understand delegate for programs that have never used C and pointers.

In C #, by using delegate, you can easily use the "+ =" (plus or equal) operator. add one or more response methods to an event in the. NET object. You can also cancel these response methods by using the very simple "-=" (minus or equal) operator. For example, the following statement adds a click event for the temp button:

      
       
Temp. Click + = new system. eventhandler (this. Test); // Add an event handling method for test.

      

In the statement that declares the event above, eventhandler is a delegate (Representative) type, which is declared in the. NET class library as follows:

      
       
Public Delegate void eventhandler (Object sender, eventargs E );

      

In this way, all functions, such as void (object parameter name, eventargs parameter name), can be used as the Click Event Response Method of the control class. As defined below, an event response method:

      
       
Private void button#click (Object sender, system. eventargs E)

      

Because events are handled by Delegate (representing the type), an event may have multiple response methods through accumulation. At the same time, you can also use a method as the response method for multiple events. (Note: Only "+ =" and "-=" can appear after the event member in the C # language class to indicate operators for adding and removing Event Response functions .)

Whether it is ASP. NET or general Windows Forms programming, in C #, basically the event response methods we encounter are described as follows:

      
       
Private void button#click (Object sender, system. eventargs E)

      

So, do the access permissions, return value types, parameters, types, and even method names of an event response method have to be fixed? The answer is: no!

Generally, there are two parameters in the event response method, one of which indicates that the event-triggering object is sender. Because the event-triggering object is unpredictable, therefore, we declare it as the object type, and all objects apply. The second parameter indicates the specific information of the event. Different types of events may be different, which is determined by the description of the event members in the class.

      
       
Delegate int myeventhandler (Object sender, toolbarbuttonclickeventargs E );

      

      
       
Private int mytest (Object sender, toolbarbuttonclickeventargs e ){}

      

You can use the following code to add an event response method to an object:

      
       
Control. event + = new myeventhandler (mytest );

      

In general, Java event processing is more direct and simple, while C # events are handled by referencing a proxy, making the program more flexible and more specific.

The loose coupling between current programs. stryon http://www.stryon.com.cn announced in Java

The development platform implements Microsoft's. net, named inet. And recently launched the inet beta3 version, which includes

Java implements a three-level event processing mechanism of C.

 

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.