What is call-back?

google了一些资料,这里整理记录一下:

=== From wikipedia.org http://en.wikipedia.org/wiki/Callback_(computer_programming) ===

// 原文中还给了Javascript和C的例子,这里就不贴出来了,google一下就有

Definition:

  In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

Design:

  There are two types of callbacks: blocking callbacks (also known as synchronous callbacks or just callbacks) and deferred callbacks (also known asasynchronous callbacks). These two design choices differ in how they control data flow at runtime. While blocking callbacks are invoked before a function returns (in the C example below: main), deferred callbacks may be invoked after a function returns. The C example below is a blocking callback. Deferred callbacks are often used in the context of I/O operations or event handling. While deferred callbacks imply the existence of multiple threads, blocking callbacks often (but not always) rely on a single thread. This means that blocking callbacks are not commonly used for synchronization or delegating work to another thread.

Implementation: // 摘抄了部分

  C, C++ and Pascal allow function pointers as arguments to other functions. Other languages, such as JavaScriptLuaPythonPerl and PHP, simply allow a function object to be passed through.

  In object-oriented programming languages without function-valued arguments, such as Java, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation. Such objects are effectively a bundle of callbacks, plus the data they need to manipulate. They are useful in implementing various design patterns such as VisitorObserver, and Strategy.

=== From stackoverflow.com http://stackoverflow.com/questions/8736378/what-is-a-callback-in-java ===

What is a callback in java?

Answer1:

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer. -- Paul Jakubik , "Callback Implementations in C++"

 

 

Answer2:

Maybe an example would help.

Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.

 

还有其他若干解答,就不贴了,下面贴一个从别人blog上找到的代码:

原文地址:http://cuishen.iteye.com/blog/438428

看过spring、hibernate源码的朋友对callback回调模式应该并不陌生,用一句话来概括就是:“if you call me, i will call back”,说白了,就是有相互依赖关系的两个类之间的互相调用,现在看看下面的代码模型:

package com.cuishen.callback;

public class Context implements A.Callback {

    private A a;
    
    public void begin() {
        System.out.println("begin ...");
    }

    public void end() {
        System.out.println("end ...");
    }
    
    public Context() {
        this.a = new A(this);
    }
    
    public void doSomething() {
        this.a.doIt();
    }
    
    public static void main(String args[]) {
        new Context().doSomething();
    }
}


package com.cuishen.callback;

public class A {
    
    private final Callback callback;
    
    public static interface Callback {
        public void begin();
        public void end();
    }
    public A(Callback callback) {
        this.callback = callback;
    }
    public void doIt() {
        callback.begin();
        System.out.println("do something ...");
        callback.end();
    }
}

上面的代码模型其原型是出自hibernate里的org.hibernate.jdbc.JDBCContext 和 org.hibernate.jdbc.ConnectionManager两个类,从上面的模型不难看出:Context类实现了A类的Callback接口,在Context类的构造器里将自己注入了A类,在Context类里调用A类的doIt()方法,这时就是:you call me;在doIt()方法体里调用了Context类的begin()和end()方法,这时就是:i call back。Context类 和 A类相互依赖,互相调用 

在hibernate的源代码里大量使用了上面的callback回调模型,又如:org.hibernate.jdbc.JDBCContext 和 org.hibernate.impl.SessionImpl等等,可以自己去看源代码,这里不再赘述。 

当然上面提到的模型中的两个类也可以写在同一个类里面,定义的Callback接口可以用内部匿名类来实现,比如下面的一个简单的dao实现:

 1 package com.cuishen.callback;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.SQLException;
 6 
 7 public class Dao {
 8     private interface Callback {
 9         Object doIt(Connection conn) throws SQLException;
10     }
11     private Object execute(Callback callback) throws SQLException {
12         Connection conn = openConnection(); // 开启数据库连接
13         try { return callback.doIt(conn); } // 执行具体操作并返回操作结果
14         finally { closeConnection(conn); } // 关闭数据库连接
15     }
16     
17     public Object sqlQuery(final String sql) throws SQLException {
18         return execute(
19             new Callback() {
20                 public Object doIt(Connection conn) throws SQLException {
21                     return conn.createStatement().executeQuery(sql);
22                 }
23             }
24         );
25     }
26     
27     public Connection openConnection() throws SQLException {
28         return DriverManager.getConnection("", null);
29     }
30     public void closeConnection(Connection conn) throws SQLException {
31         if(conn != null && !conn.isClosed()) {
32             conn.close();
33         }
34     }
35 }

 

 

posted @ 2013-06-09 17:22  rldts  阅读(313)  评论(0编辑  收藏  举报