接口回调
举例:
- 老板现在想要完成某个工作
- 于是通知员工去完成功能
- 员工开始工作
- 工作完成后通知老板
- 老板得知员工完成工作
1 定义回调接口
package 接口回调;
public interface CallBackInterface {
void callBack();
}
2 定义要被回调的实现类(Boss)
package 接口回调;
public class Boss implements CallBackInterface{
private Employee employee;
public void setEmployee(Employee employee) {
System.out.println("老板雇佣员工!");
this.employee = employee;
employee.setCallBackInterface(this);
}
public Employee getEmployee() {
return employee;
}
public void bossAskedEmployeeToWork(){
if (employee!=null){
System.out.println("老板叫员工工作");
employee.work();
}
}
@Override
public void callBack() {
System.out.println("员工告诉老板我工作做完了!");
}
}
3 定义员工类
package 接口回调;
public class Employee {
private CallBackInterface callBackInterface;
public void setCallBackInterface(CallBackInterface callBackInterface) {
this.callBackInterface = callBackInterface;
}
public void work(){
System.out.println("员工开始工作");
if (callBackInterface!=null){
callBackInterface.callBack();
}
}
}
4 测试
package 接口回调;
public class Test {
public static void main(String[] args) {
Boss boss = new Boss();
boss.setEmployee(new Employee());
boss.bossAskedEmployeeToWork();
}
}
boss.setEmployee(new Employee());
boss.bossAskedEmployeeToWork();
}
}