[Java/Android] Understanding of the callback mechanism

From the first contact with the callback mechanism until now, I have not understood the process and principle. It wasn't until recently that I spent a long time on the Internet that I suddenly understood. For me, an Android novice, it is still a very happy thing.

Today, I hereby write down my humble opinion on the callback mechanism, and also take it as a souvenir.

Let's start with a little story.

----------------------------------------------------------------------

                             gorgeous dividing line

----------------------------------------------------------------------


One day Emperor Qianlong wanted to know how local government Suzhou (Local) was catching thieves and how food was being produced, so he asked an imperial commissioner, Xiao Shuanzi (QinChai), and said, "Let me go to the locality to see if thieves are caught." There is a reward for 20, and a reward for producing 50 tons of food.


So Xiaoshuanzi went to Suzhou with the imperial decree. When they got to Suzhou, Xiao Shuanzi didn't say anything, just watched.


The emperor and the locality originally knew that there was the position of the imperial envoy, with this concept, and the role of the imperial envoy, supervising the locality and implementing the emperor's orders. (Interface and its methods)


There are also residences of imperial envoys in the Suzhou government.


As soon as this little bolt came, he was assigned to this residence.


In Suzhou, thieves are still caught every day and food is produced. Xiaoshuo also followed.


Until one day, Suzhou caught 20 thieves. At this time, Xiao Shuanzi took out the imperial decree of Qianlong, "Fengtian transport, the emperor's edict said: reward a thousand taels of silver".


Another day, the grain output reached 50 tons. Xiao Shuanzi took out the imperial decree, "Follow the sky to carry it, and the emperor's edict said: The reward is ten thousand taels."


At this point, the two imperial edicts of Qianlong were executed by Xiao Shuanzi.

----------------------------------------------------------------------

                             gorgeous dividing line

----------------------------------------------------------------------

What does it mean to tell this little story? In fact, this story contains the true meaning of the callback mechanism. So what is this truth? Don't worry, let's use the code to implement the little story above.


The official position of the imperial commissioner (interface)

package callback.test;
public interface QinChai {

    /*The official position of QinChai (imperial envoy) has these two rights, but how to do it is given by the emperor
     * This is actually a Listener
     */
    // look at the place to catch the thief
    public void onCatchTheftDone();
    //See where food is produced
    public void onMakeGrainDone();
}<strong>
</strong>


King class (think)

package callback.test;
public class King {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        King qianLong = new King();
        qianLong.wantToKnowLocal();
    }
    
    public King(){
        
    }
    
    public void wantToKnowLocal(){
        System.out.println("Qianlong: I want to know how many thieves Suzhou caught and how much food they produced");
        Local suZhou = new Local();
        System.out.println("Qianlong: Xiaoshuan, you show me, if you catch a thief, you will be rewarded 50 taels of silver and 1000 taels of silver; if you produce 50 tons, the reward will be 10,000 taels!");
        //Qianlong sent Xiaoshuanzi to Suzhou and told Xiaoshuanzi what to do
        suZhou.welcomeQinChai(new QinChai(){

            public void onCatchTheftDone() {
                // TODO Auto-generated method stub
                System.out.println("Small emboli: transported by the sky, the emperor said: catch 20 thieves, reward 1,000 taels of silver!");
            }

            public void onMakeGrainDone() {
                // TODO Auto-generated method stub
                System.out.println("Small emboli: transported by Fengtian, the emperor said: 50 grains, 10,000 taels of bounty!");
            }
        });
    }

}

local class

package callback.test;

public class Local{

    //The position of the imperial consignment is empty until the little embolism comes.
    private QinChai qinChaiDaRen = null;

    private Thread catchTheft  = null;
    private Thread makeGrain = null;
    private Thread otherThing = null;
    
    public Local(){
        localShouldDo();
        doLocalShouldDo ();
    }
    
    private void localShouldDo(){
        System.out.println("Where: I can catch thieves, produce food, and do other things!");
        catchTheft = new Thread(){
            public void run() {
                super.run();
                catchTheft();
            }
        };
        makeGrain = new Thread(){
            public void run() {
                super.run();
                makeGrain();
            }
        };
        otherThing = new Thread(){
            public void run() {
                super.run();
                doOther();
            }
        };
    }
    
    private void doLocalShouldDo(){
        System.out.println("Location: start work");
        catchTheft.start();
        makeGrain.start();
        otherThing.start();
    }
    
    private void catchTheft(){
        for(int i = 0;i < 40;i++){
            System.out.println("Location: catch the thief" + i + "a");
            if(null != qinChaiDaRen && i == 20){
                qinChaiDaRen.onCatchTheftDone();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace ();
            }
        }
    }

    private void makeGrain(){
        for(int i = 0;i < 60;i++){
            System.out.println("Location: Grain production" + i + "tons");
            if(null != qinChaiDaRen && i == 50){
                qinChaiDaRen.onMakeGrainDone();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace ();
            }
        }
    }
    
    private void doOther(){
        System.out.println("Location: other things...");
    }
    
    public void welcomeQinChai(QinChai qinchai){
        System.out.println("Location: Welcome to the Imperial Commissioner!");
        this.qinChaiDaRen = qinhai;
    }
}

operation result:

Qianlong: I want to know how many thieves Suzhou caught and how much food they produced
Place: I can catch thieves, produce food, and do other things!
Place: start to work
Qianlong: Xiaoshuanzi, let me have a look. If you catch a thief, you will be rewarded with 20 taels of silver; if the output is 50 tons, the reward will be 10,000 taels!
Place: other things. . .
Location: 0 thieves caught
Place: 0 tons of grain
Place: Welcome to the Imperial Commissioner!
Place: 1 ton of grain
Location: 1 thief caught
Location: 2 thieves caught
Place: 2 tons of grain
Place: 3 tons of grain
Location: 3 thieves caught
Place: 4 tons of grain
Location: 4 thieves caught
Location: 5 thieves caught
Place: 5 tons of grain
Place: 6 tons of grain
Location: 6 thieves caught
Place: 7 tons of grain
Location: 7 thieves caught
Location: 8 thieves caught
Place: 8 tons of grain
Location: 9 thieves caught
Place: 9 tons of grain
Place: 10 tons of grain
Location: 10 thieves caught
Location: 11 thieves caught
Place: 11 tons of grain
Place: 12 tons of grain
Location: 12 thieves caught
Location: 13 thieves caught
Place: 13 tons of grain
Location: 14 thieves caught
Place: 14 tons of grain
Location: 15 thieves caught
Place: 15 tons of grain
Place: 16 tons of grain
Location: 16 thieves caught
Location: 17 thieves caught
Place: 17 tons of grain
Location: 18 thieves caught
Place: 18 tons of grain
Place: 19 tons of grain
Location: 19 thieves caught
Place: 20 tons of grain
Location: 20 thieves caught
Xiaoshuanzi: It is carried by the sky, and the emperor edicts: catch 20 thieves and reward them with a thousand taels of silver!
Place: 21 tons of grain
Location: 21 thieves caught
Location: 22 thieves caught
Place: 22 tons of grain
Location: 23 thieves caught
Place: 23 tons of grain
Location: 24 thieves caught
Place: 24 tons of grain
Location: 25 thieves caught
Place: 25 tons of grain
Place: 26 tons of grain
Location: 26 thieves caught
Place: 27 tons of grain
Location: 27 thieves caught
Place: 28 tons of grain
Location: 28 thieves caught
Location: 29 thieves caught
Place: 29 tons of grain
Place: 30 tons of grain
Location: 30 thieves caught
Place: 31 tons of grain
Location: 31 thieves caught
Place: 32 tons of grain
Location: 32 thieves caught
Place: 33 tons of grain
Location: 33 thieves caught
Place: 34 tons of grain
Location: 34 thieves caught
Location: 35 thieves caught
Place: 35 tons of grain
Location: 36 thieves caught
Place: 36 tons of grain
Place: 37 tons of grain
Location: 37 thieves caught
Place: 38 tons of grain
Location: 38 thieves caught
Location: 39 thieves caught
Place: 39 tons of grain
Place: 40 tons of grain
Place: 41 tons of grain
Place: 42 tons of grain
Place: 43 tons of grain
Place: 44 tons of grain
Place: 45 tons of grain
Place: 46 tons of grain
Place: 47 tons of grain
Place: 48 tons of grain
Place: 49 tons of grain
Place: 50 tons of grain
Xiaoshuanzi: It is carried by Fengtian, and the emperor said: 50 grains and 10,000 taels of bounty!
Place: 51 tons of grain
Place: 52 tons of grain
Place: 53 tons of grain
Place: 54 tons of grain
Place: 55 tons of grain
Place: 56 tons of grain
Place: 57 tons of grain
Place: 58 tons of grain
Place: 59 tons of grain

From the above results it can be seen that:

Xiaoshuozi issued an imperial decree to reward when the local thieves reached 20 and the output reached 50. And this is what Qianlong told in advance.


----------------------------------------------------------------------

                             gorgeous dividing line

----------------------------------------------------------------------

Get out of this fun story.

Small plug: An interface is defined, and some functions are declared. But can't do it by itself.

Qianlong: The initiator of monitoring, create an instance of the interface, implement the function of the interface, and pass the interface to the class that wants to monitor.

Locality (Suzhou): The listener provides a setter function (welcomeQinchai) that accepts an instance of the interface, and has a location to accommodate this instance (as in the above example, the location of the imperial commissioner reserved in the locality).


So, here comes the true meaning of the callback mechanism. The interface instance created by the listener initiator is passed to the listener through the listener's setter function. Therefore, the listener can call the content that the listener has implemented when the condition is met by referring to this instance.

Essence = pass the interface instance.

Haha, I don't know if I'm right. If there is something wrong, please advise! ! ! This article ends here for now.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325856418&siteId=291194637