}
public void doWork() {
System.out.println(name + " is doing working...");
//do somtething.....
for (int i = 0; i < 10; i++) {
System.out.println("sheep" + i);
}
System.out.println(name + " was finished work!");
//tell the boss what has happend,这里就是boss的回调方法
boss.getStaffEvent(this, event);
}
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 Boss getBoss() {
return boss;
}
public void setBoss(Boss boss) {
this.boss = boss;
}
}
测试类:
Java代码
package com.wxy.callback;
public class StaffBossTest {
public static void main(String args[]) {
//初始化员工和主管
Boss boss = new Boss("boss");
Staff staffA = new Staff("staffA", boss);
Staff staffB = new Staff("staffB", boss);
//主管发放了两个新任务
Event event1 = new EventA();
Event event2 = new EventB();
//员工接受任务开始干活
staffA.setEvent(event1);
staffB.setEvent(event2);
//员工干晚活,及时向主管反馈工作情况
staffA.doWork();
staffB.doWork();
}
}
测试结果:
Java代码
staffA was finished work!
the msg what the boss received is--staffA:job has been finished!
staffB is doing working...
sheep0
sheep1
sheep2
sheep3
sheep4
sheep5
sheep6
sheep7
sheep8
sheep9
staffB was finished work!
the msg what the boss received is--staffB:job has been finished!
可以看到,当员工完成工作时(即触发某事件时),staff对象调用boss对象的方法,实现回调功能。设计模式中,观察者模式也是一个典型的应用回调机制的例子。