演示一个最基本的回调流程
/**
* Created by baodong on 6/6/15.
*/
public interface event {
public String someEvent();
}
/**
* Created by baodong on 6/6/15.
*/
public class eventA implements event {
@Override
public String someEvent() {
return "事件A...";
}
}
/**
* Created by baodong on 6/6/15.
*/
public class eventB implements event {
@Override
public String someEvent() {
return "事情B...";
}
}
/**
* Created by baodong on 6/6/15.
*/
public class Boss {
private String name;
/**
* 老板,回调函数.员工完成工作后需要调用。
* @param worker
* @param event
*/
public void callBackBoss(Worker worker, event event){
System.out.println("老板回调函数::"+worker.getName()+" "+event.someEvent());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boss(String name){
this.name = name;
}
}
/**
* Created by baodong on 6/6/15.
*/
public class Worker {
private String name;
private Boss boss;
private event event;
/**
* 构造员工类
* @param name
* @param boss
*/
public Worker(String name, Boss boss){
this.name = name;
this.boss = boss;
}
/**
* 工作,主逻辑。完成后需要回调老板的方法。
* @throws InterruptedException
*/
public void doWork() throws InterruptedException {
System.out.println(name+"在努力地工作ing。。。");
Thread.sleep(1000);
System.out.println(name+"已经完成工作。");
boss.callBackBoss(this, event);
}
public Boss getBoss() {
return boss;
}
public void setBoss(Boss boss) {
this.boss = boss;
}
public event getEvent() {
return event;
}
public void setEvent(event event) {
this.event = event;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Boss boss = new Boss("老板");
Worker workerA = new Worker("workerA", boss);
Worker workerB = new Worker("workerB", boss);
eventA eventA = new eventA();
eventB eventB = new eventB();
workerA.setEvent(eventA);
workerA.doWork();
System.out.println("---------分割线---------");
workerB.setEvent(eventB);
workerB.doWork();
}
}
输出结果:
workerA在努力地工作ing。。。
workerA已经完成工作。
老板回调函数::workerA 事件A...
---------分割线---------
workerB在努力地工作ing。。。
workerB已经完成工作。
老板回调函数::workerB 事情B...
Process finished with exit code 0