本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
What I asked about is "callback" in Java. This is a design pattern. There are exact definitions for call back in most Java text books.
Simply speaking, call back means that the server calls the client. Usually, the client wants to obtain some service and it calls a method of the server object, the server method should offer some service. In some cases, however, the server (object) just IN TURN calls another method of the client object. This design pattern is widely used in Java AWT event model. If you use JBuilder generate GUI code, all the event listeners call back the containner. Here the workflow is: The container or its contained object such as a button fires an event to the event listener, the eventlistener in turn calls a method of the container.
Our Java objects live in the JVM. Without the infrastructure and service, Java objects cannot exisit. In this context, JVM is the "server" and our Java objects are "client".
Java Object has a method called finalize(),
it is designed for JVM to call back (to clean up) as JVM does the garbage collection.
Likely, Applet and Servlet have a method called destroy(), which is called by Applet Container and Servlet Container as JVM unload Applet and Servlet. This is anpther case of callback in Java. In addition, EJB have some methods for EJB container to call back, for instance, ejbLoad(), ejbStore(), ...
Well, the following is the rule: We, application programmer never, never, never call finalize(), destroy(), .... they are designed for container to call back. However, we are require to override these callback methods in some cases. For instance, we may need to close DB connection in the destroy() method of a DB Servlet.
更多精彩文章及讨论，请光临枫下论坛. 网址: rolia.net/zh