Callback function analysis

example

You go to a store to buy something, and it happens that the item you want is out of stock, so you leave your phone number with the clerk, and after a few days the store has stock, the clerk calls you, and then you receive a call Then went to the store to pick up the goods.

In this example, contacting you by phone is the callback function . You tell the clerk to let the clerk contact you by phone , which is called the registration callback function. When the store has stock later, it is called triggering the callback-related event , and the clerk calls you, which is called calling The callback function, you go to the store to pick up the goods is called responding to the callback event.

Code example:

using UnityEngine;

// 定义一个回调函数类
// 类里有一个求和方法,要求在求和结束后需要将结果显示出来
public class Callback : MonoBehaviour
{
    
    
    public delegate void callback(int a);

    public void AddNum(int a, int b, callback call)
    {
    
    
        int count = a + b;
        call(count);
    }
}

If a delegate is used here, the function can be conveniently used as a parameter, and the function only needs to satisfy the return value and parameter types that are the same as the delegate.

using UnityEngine;

// 在这个类里面调用上个类的求和方法
// 根据要求,添加显示方法,将求和之后的数据显示出来
public class Test : MonoBehaviour
{
    
    
    public int x;
    public int y;

    Callback cb = new Callback();

    public void Start()
    {
    
    
        cb.AddNum(x, y, Show);
    }

    void Show(int z)
    {
    
    
        print(z);
    }
}

Result:
insert image description here
The role of the callback function is usually to perform another action immediately after completing an action, but you are not sure what the action will do, you can make different changes according to different needs.

Parsing on function modules

Programming is divided into two categories: system programming and application programming. The so-called system programming, in simple terms, is to write a library; and application programming is to use the various libraries written to write a program with a certain function, that is, an application. System programmers will leave some interfaces, ie API (application programming interface), to the libraries they write for use by application programmers. So in the abstraction layer diagram, the library is under the application.

When the program is running, under normal circumstances, the application program (application program) will often call the pre-prepared functions in the library through the API. But some library functions require the application to pass it a function first, so that it can be called at the right time to complete the target task. The function that is passed in and then called is called the callback function. For example, a hotel provides a wake-up service, but requires travelers to decide how to wake up. It can be to make a room call, or send a waiter to knock on the door. If you sleep too hard for fear of delaying things, you can also ask for a basin of water to be poured over your head. Here, the behavior of "wake up" is provided by the hotel, which is equivalent to a library function, but the way to wake up is determined by the passenger and told to the hotel, that is, the callback function. The action of the passenger telling the hotel how to wake him up, that is, the action of passing the callback function into the library function, is called to register a callback function. As shown below (image source: Wikipedia):

insert image description here
As you can see, the callback function is usually at the same abstraction layer as the application (because what callback function is passed in is determined at the application level). The callback becomes a high-level call to the bottom layer, and the bottom layer goes back to call the high-level process. (I think) this should be the earliest application of callbacks, and the reason for its name.

https://www.zhihu.com/question/19801131

actual code parsing

https://www.zhihu.com/question/19801131/answer/26586203

Let roommates write homework directly

Unable to stand the classmate's stubbornness, the "good Chinese roommate" agreed. How to achieve it.
Revisit the whole process of doing the homework

Callback method In the above example of "let the roommate write the homework directly", the meaning of callback has actually been reflected. The heart of the scene is that the student is about to do the homework.

#The homework to be solved String aHomeWork = “1+1=?”;
#The roommate writes the answer String theAnswer = roomMate.getAnswer(aHomeWork); #The
student calls and writes the answer to the homework. (That is, this step is not called) student.doHomeWork(aHomeWork, theAnswer); #This
method must be called for homework, and this method must be called by roommates according to demand. Obviously, the roommate has to keep a reference to the classmate in order to call it normally.
#lampdengdeng~
#The roommate said, when you call the getAnswer method, you need to put your own reference in it in addition to the incoming assignment. So I'm done, just call your homework method directly. roomMate.getAnswer(aHomeWork,student);

Full code:


	public class Student {
    
    
	
	    public void doHomeWork(String homeWork, String answer) {
    
    
	        System.out.println("作业本");
	        if(answer != null) {
    
    
	            System.out.println("作业:"+homeWork+" 答案:"+ answer);
	        } else {
    
    
	            System.out.println("作业:"+homeWork+" 答案:"+ "(空白)");
	        }
	
	    }
	
	    public static void main(String[] args) {
    
    
	        Student student = new Student();
	
	        String aHomeWork = "1+1=?";
	
	        RoomMate roomMate = new RoomMate();
	        roomMate.getAnswer(aHomeWork,student);
	    }
	}
	public class RoomMate {
    
    
	
	    public void getAnswer(String homework, Student student) {
    
    
	        if("1+1=?".equals(homework)) {
    
    
	            student.doHomeWork(homework, "2");
	        } else {
    
    
	            student.doHomeWork(homework, "(空白)");
	        }
	    }
	}

Results of the:

Workbook
Homework: 1+1=? Answer: 2

callback method

In the above example of "let the roommate write the homework directly", the meaning of callback has actually been reflected.
The heart of the scene is that the student is about to do the homework.

Brief description : The student told the roommate what homework to do and gave the roommate his own citation. The roommate gets the homework, and after finishing the work, he directly refers to the student and invokes the method of his homework to complete the task of ghostwriting the homework.

A little more complicated description : The student's method of doing homework has two parameters, one is the homework question (known), and the other is the homework answer (unknown). In order to help him write his homework, his roommate provided a method. The method has two parameters, one is the homework title, and the other is the student's reference (you need to know where to write the answer). When the program is executed, the student only needs to call the roommate's ghostwriting method. Once the roommate gets the answer, because there is a reference from the student, he directly finds the corresponding method to help him complete the homework.

A little more complicated to describe : the student invoked the roommate's substitute homework method, registered the title and his own citation. When the roommate's homework writing method is called, after completing the homework according to the topic, the classmate's homework writing method will be called back to complete the homework.

Re-abstract description : class A calls method b of class B (passing in relevant information), and after the method of class B is executed, it will write the result to (recall) method a of class A to complete the action. (Actually, method a is the legendary callback method)

The most abstract description : call, callback.

However, there is a problem here. The above uses a reference to the incoming object.
But if you just want to call a method of the object, passing in a whole reference will break security.


anonymous inner class

作者:字非易
链接:https://www.zhihu.com/question/19801131/answer/26586203
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

package org.futeng.designpattern.callback.test1;

public class RoomMate {
    
    

    public void getAnswer(String homework, DoHomeWork someone) {
    
    
        if("1+1=?".equals(homework)) {
    
    
            someone.doHomeWork(homework, "2");
        } else {
    
    
            someone.doHomeWork(homework, "(空白)");
        }
    }

    public static void main(String[] args) {
    
    

        RoomMate roomMate = new RoomMate();

        roomMate.getAnswer("1+1=?", new DoHomeWork() {
    
    

            @Override
            public void doHomeWork(String question, String answer) {
    
    
                System.out.println("问题:"+question+" 答案:"+answer);
            }
        });
    }
}

I saw the slightly strange line of roomMate.getAnswer(“1+1=?”, new DoHomeWork() {. In fact, the new one here is an anonymous inner class of the DoHomeWork interface. I think everyone should think about it by themselves. Call + antidote, how is this process implemented . As for whether to use anonymous inner classes or not, it depends on the specific usage scenario. Ordinary classes are not direct enough, and the syntax of anonymous inner classes does not seem to be friendly enough.

Advantages of callback methods

The biggest advantage of the callback method is that it is asynchronous, which is why it is most widely used.
The following will continue to use "China's good roommate" to implement the callback method asynchronously.

The callback interface does not need to be changed

public interface DoHomeWork {
    
    
    void doHomeWork(String question, String answer);
}

In order to reflect the meaning of asynchronous, we set up a difficult question for good roommates, hoping that good roommates can think more time.

Student student = new Student(); String homework = "When x tends to 0, sin(x)/x
=?";
#Create a new ask method for students, in which another thread is opened to wait for the result of the callback method feedback. student.ask(homework, new RoomMate());
#ask method is as follows public void ask(final String homework, final RoomMate roomMate) { new Thread(new Runnable() {

        @Override
        public void run() {
            roomMate.getAnswer(homework, Student.this);
        }
    }).start();

    goHome();
}

#The newly opened thread is purely used to wait for the good roommate to finish writing. Because of the 3 second wait time set in the good roommate class, you can see that the goHome method will execute first.
#Means that the student can do his own thing after telling his good roommate to do his job, and does not need to block synchronously to wait for the result.
#Once the good roommate completes the role and writes it into the workbook, the scene will end.



public class Student implements DoHomeWork{
    
    

@Override
public void doHomeWork(String question, String answer) {
    
    
    System.out.println("作业本");
    if(answer != null) {
    
    
        System.out.println("作业:"+question+" 答案:"+ answer);
    } else {
    
    
        System.out.println("作业:"+question+" 答案:"+ "(空白)");
    }
}

public void ask(final String homework, final RoomMate roomMate) {
    
    
    new Thread(new Runnable() {
    
    

        @Override
        public void run() {
    
    
            roomMate.getAnswer(homework, Student.this);
        }
    }).start();

    goHome();
}

public void goHome(){
    
    
    System.out.println("我回家了……好室友,帮我写下作业。");
}

public static void main(String[] args) {
    
    
    Student student = new Student();
    String homework = "当x趋向于0,sin(x)/x =?";
    student.ask(homework, new RoomMate());

}
}
public class RoomMate {
    
    

    public void getAnswer(String homework, DoHomeWork someone) {
    
    
        if ("1+1=?".equals(homework)) {
    
    
            someone.doHomeWork(homework, "2");
        } else if("当x趋向于0,sin(x)/x =?".equals(homework)) {
    
    

            System.out.print("思考:");
            for(int i=1; i<=3; i++) {
    
    
                System.out.print(i+"秒 ");
                try {
    
    
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
            System.out.println();
            someone.doHomeWork(homework, "1");
        } else {
    
    
            someone.doHomeWork(homework, "(空白)");
        }
    }

}

Guess you like

Origin blog.csdn.net/weixin_43757333/article/details/123025299