Java Callback mechanism parsing

Source: Internet
Author: User

There is always a certain interface between the modules, which can be divided into three categories: synchronous invocation, callback and asynchronous invocation, from the interface invocation mode. Synchronous invocation is a kind of blocking call, which is also often used in writing programs, and callback is a two-way invocation pattern, that is, the called interface is called at the same time will call the other side of the interface, this sentence may be a bit around, and so on, such as the following examples; asynchronous invocation is a similar message or event mechanism, Solve the problem of synchronous blocking, for example: a notice B, they walk each road, do not affect each other, do not like synchronous call, a notice B, must wait until B after the end, a just continue to go. Callbacks are fundamental to asynchrony, so the following emphasis is on the callback mechanism.

For the moment, let's not discuss some of the terminology and operating mechanisms of callbacks, first of all, why is there a callback call? The emergence of synchronous and asynchronous mechanisms do not need to say, we know that the callback mechanism why it appears? In our real life, there is the following scenario: a boss (upper module) is busy, he has no time to stare at the staff (the lower module) to work, and then he tells his employees, after the current events, to tell him the results of the work. This example is actually a callback + asynchronous example, another example, a programmer wrote a program A, which reserved the callback function interface, and encapsulated the program, Programmer b Let a call its own program B in a method, so he through the interface in a called back to the method in B, You may be indefinitely here, and you will continue to explain why the callback occurred. Next we turn the above example into code, and see many people on the net finally confusing async and callbacks, so the example does not add an asynchronous call. (Note: Callbacks are not a solution to the problem of long call times, it's asynchronous!) )

Start by creating a callback interface that tells the boss how to find his way through the job: Leave the boss's office address:

/**   * This interface is the way to contact, whether it is a phone number or contact address, as  * The owner must implement  this interface @author  Administrator  *   */public  interface  callbackinterface       {public  void  execute ();  }  

Create callback object, is the boss himself, because the staff to call him after the work, so the boss must implement callback interface, or where employees go to find the Boss?

/**   * The boss appears as a top-level app, and the lower-level app (employee) doesn't know  what the * method is, so he wants to be called by a downlevel  application (employee) To implement this interface @author  Administrator  *  * */public  classimplements  callbackinterface {            @Override      publicvoid  execute () {          System.out.println ("Roger it!! "+ System.currenttimemillis ());                }  }  

Create the control class, which is the employee object, he must hold the boss's address (callback interface), even if the boss changed stubble and stubble, the office is unchanged, always find the corresponding boss.

/*** Employee class, it must be remembered that this is a bottom class, the bottom is not understand the upper service *@authorAdministrator **/   Public classEmployee {PrivateCallbackinterface CallBack =NULL; //tell the boss about the contact information, that is, register     Public voidSetcallback (Callbackinterface callBack) { This. CallBack =CallBack; }            //Workers work     Public voidDosome () {//1. Start working .         for(inti=0;i<10;i++) {System.out.println ("First" "+ i +" "It's done!" "); }                    //2. Tell the boss it's done.Callback.execute (); }  }  

Test Class Code:

 public  class   Client { public  static  void   main (string[] args) {                    Employee EMP  = new   Employee ();         //  incoming callback object (upper object), register                     Emp.setcallback (new   Boss ());  //  Open Controller object run   Emp.dosome (); }    }  

In this example, you can compare it with the example of programmer A and programmer B.

Looking at the example above, some people may think that this is not interface-oriented programming? How can it be a callback, and you think about it, our interface-oriented programming call relationship? In layer three, when the business layer calls the data layer, it does not need to pass the business layer itself to the data layer, and this is an upper layer call the underlying relationship, such as when we use the framework, the general direct call to the framework provided by the API can be, but the callback is different, when the framework does not meet the requirements, We want the framework to call its own class method, how to do it? There's no way to change the frame. Many excellent frameworks are almost all related interfaces, we just need to implement the relevant interface, we can complete the registration, and then let the framework to call our own class at the appropriate time, remember when we use struts, when we write the action, we need to inherit the action class, Then implement the Execute () method, write our own business logic code in the Execute () method, and complete the processing of the user request. This makes it possible to guess that the framework and the container provide a large number of callback interfaces to suit individual customization.

I wonder if the above example is understood? We can now imagine the difference between filter and interceptor, the biggest difference between the two is that filter is based on a callback function that requires container support, no container is unable to callback the Dofilter () method, Interceptor is based on the reflection mechanism of Java, and is not related to containers. Does it confuse reflection with callbacks? See my blog of the Java Dynamic Agent, "Take this long, complement the short----AOP (proxy mode)."

In short, to be clear, the first thing is to understand the reason for the callback function, that is, the application of the scene, in order to clear the callback mechanism, otherwise less effort.

Finally, to give an example, in order to make our function close to perfect, we will part of the function of outsourcing to others, let others personalized customization, as for others how to achieve regardless, I have to do is to define the relevant interface, this design allows the underlying code to invoke high-level defined subroutines, enhance program flexibility, and reflection have the same wonderful, this is the real reason for the callback!

Summarize the next callback in a paragraph: when the upper module is encapsulated, it is difficult to anticipate how the underlying module will be implemented, so the upper module simply needs to define its own desired but unpredictable interface (that is, the callback interface), when the underlying module calls the upper module, according to the current needs of the implementation callback interface, and through the registration or parameter to the upper module can be implemented, so that the lower layer of the call, and the upper layer can also be based on the incoming reference to invoke the implementation of the lower layer, the flexibility of the program greatly increased. This is intended to spring JdbcTemplate as an example, but it involves more than callbacks, as well as template mode, and so on, afraid to understand the difficulties are not adopted, interested readers can self-view the relevant source code, is also a callback + internal class good example.

About the event write a very good article, paste it out: http://blog.csdn.net/coolmeme/article/details/6060787

Source

http://blog.csdn.net/bjyfb/article/details/10462555

Java Callback mechanism parsing

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.