(转载)
回调你可以这样来理解:
A发送消息给B,B处理好A要求的事情后,将结果返回给A,A再对B返回的结果来做进一步的处理。
1、回调的实现
-
-
-
-
-
- public interface CallBack {
-
-
-
-
- public void execute(Object... objects );
- }
2、 消息的发送者
-
-
-
-
-
- public class Local implements CallBack,Runnable{
-
-
-
-
- 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、 远程消息的接收者
-
-
-
-
-
- public class Remote {
-
-
-
-
-
-
- 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的世界里,那就属于“委派”。也就是说,“回调”必须是消息的发送者来处理消息结果,否则不能称之为回调。这个概念必须明确。