Design pattern-Template mode

Source: Internet
Author: User

Template design Pattern Definition:

Defining the skeleton of an algorithm in an operation, and delaying some steps into subclasses, the template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of the algorithm.

The popular point of understanding is: To complete one thing, there are a fixed number of steps, but each step according to the different objects, and implementation of different details; You can define an overall method of doing this in the parent class, and invoke the implementation of each of its steps according to the steps required to complete the event. The specific implementation of each step is done by the subclass.

Example description

To give an example: for example, our cooking can be divided into three steps (1) Preparation (2) specific cooking (3) The end of the dish for the guests to enjoy, the three is the skeleton of the algorithm, but the need to do different dishes, methods, and how to dress for the guests are different this is different implementation details.

Down we'll implement the code as follows

A. First to write an abstract dish-making parent class:

Public abstract class Dodishtemplate {        /**     * Specific entire process *    /protected void Dodish () {        this.preparation ();        This.doing ();        This.carrieddishes ();    }    /**     * Preparation * * Public    abstract void Preparation ();    /**     * Cooking * * * public    abstract void doing ();    /**     * Serving * * * public    abstract void Carrieddishes ();}

B. Down to make two tomato scrambled eggs (eggswithtomato) and braised pork (Bouilli) implements the abstract method in the parent class

/** * Tomato Scrambled egg * @author Aries */public class Eggswithtomato extends dodishtemplate{    @Override public    void Preparat Ion () {        System.out.println ("Wash and cut tomatoes, beat the eggs.") ");    }    @Override public    Void doing () {        System.out.println ("Pour the eggs into the pot, then pour the tomatoes together and fry. ");    }    @Override public    void Carrieddishes () {        System.out.println ("Put the scrambled West Red Temple eggs into the plate and end it to the guests.") ");    }}
/** * Pork * @author aries * */public class Bouilli extends dodishtemplate{    @Override public    Void Preparation () {
   system.out.println ("Cut pork and potatoes. ");    }    @Override public    Void doing () {        System.out.println ("Pour the chopped pork into a pan and fry for a while and then pour the potatoes into a stir-fry belt.") ");    }    @Override public    void Carrieddishes () {        System.out.println ("The cooked pork will be served in a bowl for the guests to eat." ");    }}

C. In the test class we will cook:

public class App {public    static void Main (string[] args) {        dodishtemplate Eggswithtomato = new Eggswithtomato () ;        Eggswithtomato.dodish ();                System.out.println ("-----------------------------");                Dodishtemplate Bouilli = new Bouilli ();        Bouilli.dodish ();    }}

This allows us to implement a complete example of using template patterns.

Template design patterns are often used in database operations, and I now use template mode to do a JDBC query template:

(1) abstract Query parent class

Public abstract class Abstractdao {    /**     * Query     * @param SQL     * @param params     * @return    */ Protected Object Find (String sql, object[] params) {        Connection conn = null;        PreparedStatement PS = null;        ResultSet rs = null;        Object obj = null;        try {            conn = jdbcutils.getconnection ();            PS = conn.preparestatement (sql);            for (int i = 0; i < params.length; i++) {                Ps.setobject (i + 1, params[i]);            }            rs = Ps.executequery ();            while (Rs.next ()) {                obj = RowMapper (rs);            }        } catch (Exception e) {            e.printstacktrace ();        } finally {            Jdbcutils.free (RS, PS, conn);        }        return obj;    }    
Protected abstract Object RowMapper (ResultSet rs) throws SQLException;

You can also add Insert, Update, and Other methods}

(2) The specific Userdao

/** * Userdao *  * @author aries * */public class Userdao extends Abstractdao {public    User finduser (int userId) { c3/>string sql = "SELECT * from t_user where userId =?";        object[] params = new object[] {userId};        Object user = Super.find (sql, params);        System.out.println (user) (user);        return (user) user;    @Override    protected Object RowMapper (ResultSet rs) throws SQLException {        User user = new User ();        User.setid (Rs.getint ("userId"));        User.setname (rs.getstring ("name"));        User.setage (Rs.getint ("Age"));        User.setsex (rs.getstring ("Sex"));        User.setaddress (rs.getstring ("Address"));        return user;    }}

(3) The user class and Jdbcutil used in the above code

public class Jdbcutils {private static String URL = "Jdbc:mysql://localhost:3306/jdbcstudy";    private static String user = "root";    private static String password = "123";        Private Jdbcutils () {} static {try {Class.forName ("com.mysql.jdbc.Driver");        } catch (ClassNotFoundException e) {throw new Exceptionininitializererror (e); }} public static Connection getconnection () throws SQLException {return drivermanager.getconnection (URL, US    er, password); } public static void Free (ResultSet rs, PreparedStatement PS, Connection conn) {if (rs! = null) {T            ry {rs.close ();            } catch (SQLException e) {e.printstacktrace ();            }} if (PS! = null) {try {ps.close ();            } catch (SQLException e) {e.printstacktrace ();        }} if (conn! = null) {try {        Conn.close ();            } catch (SQLException e) {e.printstacktrace (); }        }    }}
/** * User class *  * @author aries * */public class User {    private Integer ID;    private String name;    Private Integer age;    Private String sex;    Private String address;            Set...get omitted    }

As on the use of template mode to do the query, the parent has done the algorithm skeleton, sub-class concrete implementation of the different parts of the algorithm.

Advantages of template Mode

(1) Specific details step implementation defined in subclasses, subclass definition verbose processing algorithm does not change the overall structure of the algorithm.

(2) Code reuse of the basic technology, in the database design is particularly important.

(3) There is a reverse control structure, the operation of its subclasses is called by a parent class, and the parent class is extended by subclasses to add new behavior, which conforms to the "open and closed principle".

Insufficient

Each different implementation needs to define a subclass, which causes the number of classes to increase and the system to be larger.

Design pattern-Template mode

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.