What is a callback method in Java? (Term seems to be used loosely)

后端 未结 5 1233
误落风尘
误落风尘 2020-11-30 21:11

I don\'t understand what a callback method is and I have heard people use that term very loosely. In the Java world, what is a callback method? If someone could provide some

5条回答
  •  眼角桃花
    2020-11-30 22:09

    In Simple Words... In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.

    How are they different from calling one function from another function taking some context from the calling function? It is true that you are calling a function from another function, but the key is that the callback is treated like an Object, so you can change which Function to call based on the state of the system (like the Strategy Design Pattern).

    How can their power be explained to a novice programmer? The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze up" while downloading the new data, or you would need to refresh the entire page rather than just part of it. With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.

    Some code without a callback:

         function grabAndFreeze() {
        showNowLoading(true);
        var jsondata = getData('http://yourserver.com/data/messages.json');
        /* User Interface 'freezes' while getting data */
        processData(jsondata);
        showNowLoading(false);
        do_other_stuff(); // not called until data fully downloaded
            }
    
          function processData(jsondata) { // do something with the data
        var count = jsondata.results ? jsondata.results.length : 0;
         $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
         $('#results_messages').html(jsondata.results || '(no new messages)');
           }
    

    With Callback: Here is an example with a callback, using jQuery's getJSON:

        function processDataCB(jsondata) { // callback: update UI with results
       showNowLoading(false);
       var count = jsondata.results ? jsondata.results.length : 0;
       $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
       $('#results_messages').html(jsondata.results || '(no new messages)');
              }
    
    `   `function grabAndGo() { // and don't freeze
        showNowLoading(true);
        $('#results_messages').html(now_loading_image);
        $.getJSON("http://yourserver.com/data/messages.json", processDataCB);
        /* Call processDataCB when data is downloaded, no frozen User Interface!                              
        do_other_stuff(); // called immediately
    

提交回复
热议问题