您的位置:首页 > 编程语言 > Java开发

比较典型的java回调案例-员工老板

2015-04-06 19:18 232 查看
下面是一个典型的回调案例:公司员工工作,工作完成后主管要求员工汇报工作完成情况。
事件接口:
Java代码
package com.wxy.callback;

public interface Event {
/**
* 返回发生事件信息
* @return 事件信息
*/
public String happendEvent();

}
事件具体实现类:
Java代码
package com.wxy.callback;

public class EventA implements Event {

@Override
public String happendEvent() {
return "job has been finished!";
}

}

Java代码
package com.wxy.callback;

public class EventB implements Event {

@Override
public String happendEvent() {
return "job has been finished!";
}

}
主管类:
Java代码
package com.wxy.callback;

public class Boss {
private String name;

public Boss(String name) {
this.name = name;
}

public void getStaffEvent(Staff staff, Event event) {
System.out.println("the msg what the boss received is--" + staff.getName() + ":"
+ event.happendEvent());
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
员工类:
Java代码
package com.wxy.callback;

public class Staff {
private Event event; //事件
private String name; //员工姓名
private Boss boss; //员工所属主管

/**
* 员工构造器
* @param name 员工姓名
* @param boss 传入Boss对象,便于回调反馈工作状况
*/
public Staff(String name, Boss boss) {
this.name = name;
this.boss = boss;
}

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对象的方法,实现回调功能。设计模式中,观察者模式也是一个典型的应用回调机制的例子。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: