. Net event model tutorial (III)

Source: Internet
Author: User

Through the first two sections, you have mastered the principles and implementation methods of the. NET event model. I will introduce two alternative solutions in this section. These solutions are not recommended. Use the event model whenever possible. In addition, at the end of this section, a reader familiar with the Java language will read and discuss the differences between. NET and Java in the "event model.

Directory

  • Implement callback Using Interfaces
  • Comparison between the. NET event model and the Java event model

Implement callback Using Interfaces

The event model is actuallyCallback Function. As in the previous example, form1 calls worker, and worker (through the event model) changes the status bar information of form1. This operation is a type of callback.

As mentioned in the. NET Framework class library design guide, "delegation, interfaces, and events allow for callback. Each type has its own specific usage characteristics to make it more suitable for specific situations ." (Refer to the local SDK version and the online msdn Version)

In the event model, delegate is also used to implement callback. It can be said that the event model is a special case of delegate callback. If you have the opportunity, I will introduce the application of delegate callback in multiple threads in the multi-thread tutorial.

Let's take a look at how to use the interface to implement the callback function to achieve the effect of the previous event model.

Demo 1i: Use the interface to implement callback.

Using system; using system. threading; using system. collections; namespace percyboy. eventmodeldemo. demo1i {// note this interface public interface iworkerreport {void onstartwork (INT totalunits); void onendwork (); void onratereport (double rate );} public class worker {private const int max = consts. max; private iworkerreport report = NULL; public worker () {}// specify iworkerreport public worker (iworkerreport Report) {This. report = Report;} // After initialization, specify public iworkerreport {set {report = value;} public void dolongtimetask () {int I by setting this attribute; bool T = false; double rate; If (report! = NULL) {report. onstartwork (max) ;}for (I = 0; I <= max; I ++) {thread. Sleep (1); t =! T; rate = (double) I/(double) max; If (report! = NULL) {report. onratereport (rate) ;}} if (report! = NULL) {report. onendwork ();}}}}

You can run the compiled example to complete the same work as the event model described earlier, and ensure that the coupling degree does not increase. To call worker's form1, You need to implement an iworkerreport:

Private void button#click (Object sender, system. eventargs e) {statusbar1.text = "Getting started .... "; this. cursor = cursors. waitcursor; long tick = datetime. now. ticks; worker = new worker (); // specify iworkerreport worker. report = new myworkerreport (this); worker. dolongtimetask (); tick = datetime. now. ticks-tick; timespan Ts = new timespan (tick); this. cursor = cursors. default; statusbar1.text = string. Format ("task completed, time consumed {0} seconds. ", Ts. totalseconds);} // here iworkerreport private class myworkerreport: iworkerreport {public void onstartwork (INT totalunits) {} public void onendwork () {} public void onratereport (double rate) {parent. statusbar1.text = string. format ("completed {0: P0 }.... ", rate);} private form1 parent; Public myworkerreport (form1 form) {This. parent = form ;}}

You may already think that this implementation method, although the worker class may be missing some code, it adds a lot of code during the call. From the perspective of reuse, the event model is obviously easier to call. In addition, from an object-oriented perspective, after I understand the principles of the event model, you will feel that "events" will be more friendly.

In addition, iworkerreport contains multiple methods. Most of the time, we do not need each method. As in the preceding example, both onstartwork and onendwork are blank. If there are many methods in the interface, more code will be added to the caller.

The downloaded Source Code also contains a demo 1j, which, together with the worker class, provides a default workerreportadapter for iworkerreport (each method is blank ). In this way, the caller only needs to inherit from workerreportadapter and rewrite the method to be rewritten, which reduces the amount of code. But I think there are still many.

Note that the above Code applies (only applies because it is not an event model) the concepts of "unicast events" and "Multicast events, it supports only "unicast events ". If you want to support "Multicast events", I think you can consider adding the addworkerreport and removeworkerreport methods, and using hashtable and other data structures to store each added iworkerreport.

[Top]

 

Comparison between the. NET event model and the Java event model

(I do not know much about the Java language. If you have any mistakes, please correct me !)

The. NET event model is implemented at the language level for C #/VB. NET mainstream languages. C # provides the event keyword, while VB. NET provides the event and raiseevent keywords. As mentioned in the previous two sections, they all have their own syntax for declaring event members. The Java language does not have the concept of "events.

From the perspective of object-oriented theory ,. net class (or class instance: Object), can have: field, attribute, method, event, constructor, destructor, operators and other member types. In Java, classes only include fields, methods, constructors, destructor, and operators. Java classes do not contain attributes and events. (Although Java Bean indirectly converts the getwidth and setwidth methods into a width attribute, Java still does not regard "attribute" as a language level .) In short, Java does not support events at the language level.

Java swing is an API commonly used in the Java World to create windows forms. Java swing has a set of event models for its controls (such as buttons) to have event mechanisms.

The swing event model is similar to the interface mechanism described in this section. It uses interfaces, such as actionlistener, keylistener, and mouselistener (Note: According to Java Naming Conventions, the interface name does not use the prefix I). It also provides default implementations of some interfaces, such as keyadapter and mouseadapter. The usage is similar to that described in this section. addactionlistener, removeactionlistener, addkeylistener, removekeylistener, addmouselistener, and removemouselistener are used to increase or decrease these interfaces.

As in this example, the swing event model using the interface mechanism requires a lot of code to implement the interface or rewrite the adapter. In contrast, the. NET event model is more lightweight, and only one line of hook-up code is required.

On the other hand, we can see the swing naming method. These interfaces are named listener and listener. In contrast ,. in the. NET event model, event processing is called handler, an event processing program. One uses "Listening" and the other uses "processing". I think this reflects a kind of thinking difference.

In another example, the "processing" model refers to handle this event when a shouting event occurs, listening, it is because the outside world has been "listening" to Michael's every action (Listening). Once Michael shouted, the listener was triggered. The processing model is centered on zhangsan, while the Listening model is centered on the external environment.

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.