Detailed Java template and callback mechanism _java

Source: Internet
Author: User

A recent look at Spring's jdbctemplete template way call, the template and callback generated a strong interest, query some information, do some summary.

callback function:

A callback is the client C calling a function in service s, and then S, in turn, calls a function B in C, which is called a callback function for C. A callback function is simply a function fragment that is implemented by the user according to the callback function calling convention. A callback function is a part of a workflow that determines the timing of the invocation (callback) of a function by a workflow. Generally, C does not call B,c itself to provide b for the purpose of having s to invoke it, and C has to provide it. Since S does not know the B thy name provided by C, S will agree to B's interface specification (function prototype), and then by C, a function of S is passed ahead of it, which tells S that he is going to use the B function, which is called the registration of the callback function, R called the registration function. Both Web service and Java RMI Use callback mechanisms to access remote server programs. The callback function contains the following features:

1, belong to a part of the workflow;

2, must declare (define) according to the calling convention specified by the workflow;

3. The timing of his invocation is determined by the workflow, and the user of the callback function cannot call the callback function directly to realize the function of the workflow;

Callback mechanism:

A callback mechanism is a common design model that exposes a function within a workflow to external users, provides data to external users, or requires external users to provide data.

Java Callback mechanism:

There is always a certain interface between software modules, from the way of invocation, they can be divided into three categories: synchronous call, callback and asynchronous call.

Synchronous call: A blocking call in which the caller waits for the other party to execute before returning, which is a one-way call;

Callback: A bidirectional invocation pattern, that is, the caller also invokes the interface of the other when the interface is invoked;

Asynchronous invocation: A mechanism similar to a message or event, but its invocation is in the opposite direction, when a service of an interface receives a message, or an event occurs, proactively notifies the client (that is, the interface that invokes the client).

Callback and asynchronous invocation are very closely related: Use callbacks to implement the registration of asynchronous messages, and to implement notification of messages by asynchronous invocation.

Callback Instance

1. Callback Interface

Public interface Callback {

   String Callback ();
 }

2. Caller

public class Another {
  private Callback Callback;
  The method to invoke the implementation class is public
  void Setcallback (Callback Callback) {
    this.callback = Callback;
  }
    The specific method of calling the implementation class is public
  void DoCallback () {System.out.println (Callback.callback ()) by delegation when the business needs to be done
    ;
  }

3. Test callback function

public class Testcallcack {public
  static void Main (string[] args) {
    //Create caller's implementation class
    Another Another = new Another ();
    Registers the postback interface into the implementation class
    Another.setcallback (New Callback () {  
      @Override public
      String Callback () {return
        " are a pig ";
      }
    }";
    Execute callback function
    another.docallback ();
  }

The use of callback methods usually occurs during the use of the Java interface and abstract classes. The template method design pattern uses the mechanism of method callback, which first defines the algorithm skeleton of a particular step, and delays some steps to the design pattern implemented in subclasses. The template method design pattern allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.

Applicability of template mode design patterns:

1, a one-time implementation of the invariant part of the algorithm, and the variable algorithm left to subclass to achieve.

2. Public behavior in each subclass should be extracted and centralized in a common parent class to avoid code duplication.

3, you can control the child class extension.

Template instance:

Abstract Template Method Class:

Public abstract class Abstractsup {
    //Required Subclass implementation method public
  abstract void print ();
    Template method public
  void Doprint () {
    System.out.println ("Execute Template Method");
    for (int i = 0; i < 3; i++) {
      print ();
    }
  }
}

Subclass Implementation Template Way class:

public class subclass extends abstractsup{
  @Override
  The implementation method of the public void print () {
    System.out.println ("subclass") ");
  }

}

Template method Test class:

public class Templetetest {public
  static void Main (string[] args) {
    Subclass subclass = new Subclass ();
    Subclass.print ();
    Subclass.doprint ();
  }

The following is an in-depth introduction to the use of the spring template method, taking Jdbctemplete as an example, detailing the use of template patterns and callback mechanisms.
First take a look at the classic JDBC programming examples:

Public list<user> query () {list<user> userlist = new arraylist<user> (); 
 
  String sql = "SELECT * from User"; 
  Connection con = null; 
  PreparedStatement PST = NULL; 
  ResultSet rs = null; 
    try {con = hsqldbutil.getconnection (); 
    PST = con.preparestatement (SQL); 
 
    rs = Pst.executequery (); 
    User user = null; 
      while (Rs.next ()) {user = new user (); 
      User.setid (Rs.getint ("id")); 
      User.setusername (rs.getstring ("user_name")); 
      User.setbirth (Rs.getdate ("Birth")); 
      User.setcreatedate (Rs.getdate ("create_date")); 
    Userlist.add (user); 
  } catch (SQLException e) {e.printstacktrace (); 
      }finally{if (rs!= null) {try {rs.close (); 
      catch (SQLException e) {e.printstacktrace (); 
    } try {pst.close (); 
    catch (SQLException e) {e.printstacktrace (); 
      try {if (!con.isclosed ()) {try {    Con.close (); 
        catch (SQLException e) {e.printstacktrace (); 
    A catch (SQLException e) {e.printstacktrace ()); 
} return userlist; }


A simple query, it is necessary to do such a large pile of things, but also to deal with the exception, we do not have to comb:
1. Get connection
2. Get statement
3. Get ResultSet
4, traversing resultset and encapsulation into a collection
5, turn off the Connection,statement,resultset, but also to consider a variety of anomalies and so on.

If multiple queries produce more duplicate code, the template mechanism can then be used to observe that most of the above steps are repetitive, reusable, and that only the steps to traverse resultset and encapsulate the collection are customizable, because each table maps a different Java bean. This part of the code is no way to reuse, can only be customized.

Abstract class Code:

 public abstract class JdbcTemplate {//Template method public final Object execute (String sq 
    L) throws sqlexception{Connection con = hsqldbutil.getconnection (); 
    Statement stmt = null; 
      try {stmt = Con.createstatement (); 
      ResultSet rs = stmt.executequery (SQL); 
    Object result = Doinstatement (RS);//abstract method (custom method, required subclass implementation) return result; 
       catch (SQLException ex) {ex.printstacktrace (); 
    Throw ex; 
      Finally {try {stmt.close (); 
      catch (SQLException e) {e.printstacktrace (); 
          try {if (!con.isclosed ()) {try {con.close (); 
          catch (SQLException e) {e.printstacktrace (); 
      A catch (SQLException e) {e.printstacktrace ()); 
}}//abstract method (custom method) protected abstract Object doinstatement (ResultSet rs); }

In this abstract class, the main process of the Sun JDBC API is encapsulated, and the step to traverse resultset is placed in the abstract method Doinstatement (), which is implemented by the subclass.

Subclass Implementation Code:

public class Jdbctemplateuserimpl extends JdbcTemplate { 
 
  @Override 
  protected Object doinstatement (ResultSet RS ) { 
    list<user> userlist = new arraylist<user> (); 
     
    try { 
      user user = null; 
      while (Rs.next ()) { 
 
        user = new User (); 
        User.setid (Rs.getint ("id")); 
        User.setusername (rs.getstring ("user_name")); 
        User.setbirth (Rs.getdate ("Birth")); 
        User.setcreatedate (Rs.getdate ("create_date")); 
        Userlist.add (user); 
      } 
      return userlist; 
    } catch (SQLException e) { 
      e.printstacktrace (); 
      return null;}}} 
 

In the Doinstatement () method, we iterate over the resultset, and then we go back.

Test code:

String sql = "SELECT * from User"; 
JdbcTemplate JT = new Jdbctemplateuserimpl (); 
List<user> userlist = (list<user>) jt.execute (SQL); 

The use of the template mechanism ends here, but if you want to inherit the above parent class every time you call JdbcTemplate, it's not convenient, so the callback mechanism works.

A callback is the passing of an interface in a method parameter in which the parent class must invoke the implementation class of the interface passed in the method when calling this method.

Callback Plus template pattern implementation

Callback Interface:

Public interface Statementcallback { 
  Object doinstatement (Statement stmt) throws SQLException; 
 

Template method:

 public class JdbcTemplate {//Template method public final Object execute (statementcallback 
    Action) throws sqlexception{Connection con = hsqldbutil.getconnection (); 
    Statement stmt = null; 
      try {stmt = Con.createstatement (); 
    Object result = Action.doinstatement (RS);//callback method return result; 
       catch (SQLException ex) {ex.printstacktrace (); 
    Throw ex; 
      Finally {try {stmt.close (); 
      catch (SQLException e) {e.printstacktrace (); 
          try {if (!con.isclosed ()) {try {con.close (); 
          catch (SQLException e) {e.printstacktrace (); 
      A catch (SQLException e) {e.printstacktrace ()); The public Object query (Statementcallback stmt) throws sqlexception{return execute (stmt 
  ); } 
}

class to test:

Public Object query (final String sql) throws SQLException { 
    class Querystatementcallback implements Statementcallback {public 
 
      Object doinstatement (Statement stmt) throws SQLException { 
        ResultSet rs = Stmt.executequery (SQL); 
        list<user> userlist = new arraylist<user> (); 
 
        User user = null; 
        while (Rs.next ()) { 
 
          user = new User (); 
          User.setid (Rs.getint ("id")); 
          User.setusername (rs.getstring ("user_name")); 
          User.setbirth (Rs.getdate ("Birth")); 
          User.setcreatedate (Rs.getdate ("create_date")); 
          Userlist.add (user); 
        } 
        Return userlist 
 
      } 
 
    } 
 
    JdbcTemplate JT = new JdbcTemplate (); 
    Return Jt.query (New Querystatementcallback ()); 
  }


Why does spring not use the traditional template approach, coupled with callback?
Imagine that if there are 10 abstract methods in the parent class, and all the subclasses that inherit it are implemented in all of the 10 abstract methods, the subclasses are very bloated. And sometimes a subclass just needs to customize one of the methods in the parent class. This time will use callback callback.

In addition, the above approach basically implements the template method + callback pattern. But there is still some distance from spring's jdbctemplate. Although we have implemented the template method + callback pattern above, but relative to spring's jdbctemplate is somewhat "ugly". Spring introduces the concepts of RowMapper and ResultSetExtractor. The RowMapper interface is responsible for processing a row of data, for example, we can manipulate a row of records in the Maprow method, or encapsulate it as a entity. ResultSetExtractor is the DataSet extractor, which is responsible for traversing the resultset and processing the data according to the rules in RowMapper. The difference between RowMapper and ResultSetExtractor is that RowMapper handles a row of data and returns an entity object. Instead, ResultSetExtractor processes a collection of data and returns a collection of objects.

Of course, the above is just the rationale for the spring Jdbctemplte implementation, and more has been done within spring jdbctemplate, such as encapsulating all the basic operations into the JdbcOperations interface, And the use of jdbcaccessor to manage datasource and conversion anomalies.

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.