Friday 1 April 2016

Callback

Suppose you want to check the progress of some work. You can choose to query the status from the server regularly. But this solution sucks right? It's like asking taxi driver every 5 minutes how far away the destination is.

 class Server{  
   private int progress;  
   public int getProgress(){ return progress;  }  
   public void copy() {  
     while(progress <100){  
       try{  
         Thread.sleep(10);  
         progress++;  
       }catch(InterruptedException e){}  
     }  
   }  
 }  
 public class NoCallbackClient {  
   private Server server = new Server();  
   public void call() {  
     server.copy();  
   }  
   public static void main(String[] args) throws InterruptedException{  
     final NoCallbackClient client = new NoCallbackClient();  
     Runnable r = ()->client.call();  
     new Thread(r).start();  
     System.out.print("Progress: ");  
     while(true){  
       int progress = client.server.getProgress();  
       Thread.sleep(200);  
       if(progress >= 100){  
         break;  
       }else{  
         System.out.print(progress+"% ");  
       }  
     }  
   }  
 }  

So instead of keeping asking the taxi driver, you should say to the driver, "Hey, let me know when we are 25%, 50%, 75% into our journey".

Here is what callback does.

 package callback;  
 interface IClient{  
   void callback(int i);  
 }  
 class Server{  
   private IClient client;  
   public Server(IClient client) {  
     this.client = client;  
   }  
   public void copy() {  
     for(int i=0;i<=100;i++){  
       if (i%10 == 0) {  
         client.callback(i);  
       }  
     }  
   }  
 }  
 public class CallbackClient implements IClient{  
   public void call() {  
     new Server(this).copy();  
   }  
   @Override public void callback(int i) {  
     System.out.print(i+"% ");  
   }  
   public static void main(String[] args){  
     new CallbackClient().call();  
   }  
 }  

Reference: http://blog.csdn.net/yqj2065/article/details/39481255