Callback method chestnut: The manager wants you to do something before going on a business trip. This thing is told to you through doSomething. If the thing is done, she will be notified through phoneCall. Here's the phoneCall, we call it a callback method. It
satisfies the two basics of callback. Conditions:
1.ClassA calls the X method in ClassB 2.The X method in ClassB
calls the Y method in ClassA during the execution process to complete the callback
//该类用来模拟经理类
public class Manager {
public Manager(Personel personel) {
personel.doSomething(this, "整理公司文件");
}
// 当员工做完经理让他做的事后就通过该方法通知事情结果
public void phoneCall(String result) {
System.out.println("事情" + result);
}
}
//该类用来模拟员工类
public class Personel {
public void doSomething(Manager manager,String task) {
//总经理通过doSomething方法告诉员工要做什么
System.out.println("经理要你做"+task);
String result="搞定了";
//当事情做完了我们就通过经理公布的phoneCall方法通知结果
manager.phoneCall(result);
}
}
public class Test{
public static void main(String[] args) {
//首先需要一个员工
Personel personel=new Personel();
//其次把这个员工指派给经理
new Manager(personel);
}
}
Console:
经理要你做整理公司文件
事情搞定了