(转载)
回调你可以这样来理解:
A发送消息给B,B处理好A要求的事情后,将结果返回给A,A再对B返回的结果来做进一步的处理。
1、回调的实现
- /**
- * 回调接口
- * @author KOOK
- *
- */
- public interface CallBack {
- /**
- * 执行回调方法
- * @param objects 将处理后的结果作为参数返回给回调方法
- */
- public void execute(Object... objects );
- }
2、 消息的发送者
- /**
- * 简单本地发送异步消息的类
- * @author KOOK
- *
- */
- public class Local implements CallBack,Runnable{
- /**
- * 远程接收消息的类,模拟point-to-point
- */
- private Remote remote;
- /**
- * 发送出去的消息
- */
- private String message;
- public Local(Remote remote, String message) {
- super();
- this.remote = remote;
- this.message = message;
- }
- /**
- * 发送消息
- */
- public void sendMessage()
- {
- /**当前线程的名称**/
- System.out.println(Thread.currentThread().getName());
- /**创建一个新的线程发送消息**/
- Thread thread = new Thread(this);
- thread.start();
- /**当前线程继续执行**/
- System.out.println("Message has been sent by Local~!");
- }
- /**
- * 发送消息后的回调函数
- */
- public void execute(Object... objects ) {
- /**打印返回的消息**/
- System.out.println(objects[0]);
- /**打印发送消息的线程名称**/
- System.out.println(Thread.currentThread().getName());
- /**中断发送消息的线程**/
- Thread.interrupted();
- }
- public static void main(String[] args)
- {
- Local local = new Local(new Remote(),"Hello");
- local.sendMessage();
- }
- public void run() {
- remote.executeMessage(message, this);
- }
- }
3、 远程消息的接收者
- /**
- * 处理消息的远程类
- * @author KOOK
- *
- */
- public class Remote {
- /**
- * 处理消息
- * @param msg 接收的消息
- * @param callBack 回调函数处理类
- */
- public void executeMessage(String msg,CallBack callBack)
- {
- /**模拟远程类正在处理其他事情,可能需要花费许多时间**/
- for(int i=0;i<1000000000;i++)
- {
- }
- /**处理完其他事情,现在来处理消息**/
- System.out.println(msg);
- System.out.println("I hava executed the message by Local");
- /**执行回调**/
- callBack.execute(new String[]{"Nice to meet you~!"});
- }
- }
执行Local类的main方法。
注意Local类中红色背景的那行:
remote.executeMessage(message, this);
executeMessage方法需要接收一个message参数,表示发送出去的消息,而CallBack参数是他自己,也就是这里的this。表示发送消息后,由Local类自己来处理,调用自身的execute方法来处理消息结果。
如果这里不是用this,而是用其他的CallBack接口的实现类的话,那就不能称之为“回调”了,在OO的世界里,那就属于“委派”。也就是说,“回调”必须是消息的发送者来处理消息结果,否则不能称之为回调。这个概念必须明确。