java design patterns ---- template mode, hand line and a JDBCTemplate

Template mode (Template Method Pattern)

Definition of a skeleton of an algorithm and allows subclasses provide an implementation for one or more steps.

Template methods such subclasses without changing the structure of the algorithm, the algorithm to redefine certain steps.

Belonging to the Behavioral design patterns.

Applicable scene:

1. Disposable achieve a constant part of the algorithm, and variable behavior left a subclass to achieve.

2. subclass each common behavior is extracted and concentrated to a common parent, thereby avoiding the code repetition.

 

Reality scene (by plane):

------ ----- find tickets pitted the security of aircraft / temporary problems, leaving ------ flight completion / return place

Process Code:

/**
 * @Author Darker
 * @Descrption 坐飞机的流程
 * @Date : Created in 9:41 2020-3-13
 */
public abstract class TakeAPlane {

    //坐飞机的流程是固定的
    protected final void fly(){

        //买票
        this.buyTick();

        //安检
        this.SecurityCheck();

        //实现流程的微调,如果流程不用微调,可以不用
        if(isAnyThing()){
            //返回
            this.goBack();
        }else{
            //上飞机
            this.selectPlane();
            //飞行完成
            this.CompletionOfFlight();
        }

    }

    protected final void buyTick(){
        System.out.println("买票");
    }

    protected final void SecurityCheck(){
        System.out.println("安检");
    }

    //钩子方法
    protected boolean isAnyThing(){return false;}

    protected final void goBack(){
        System.out.println("临时有事,原路回家");
    }

    protected abstract void selectPlane();

    protected final void CompletionOfFlight(){
        System.out.println("一路平安,飞行完成");
    }
}

/**
 * @Author Darker
 * @Descrption
 * @Date : Created in 10:07 2020-3-13
 */
public class TakeAPlaneToHaiHang extends TakeAPlane{

    private boolean anyThing = false;

    public TakeAPlaneToHaiHang(boolean anyThing){
        this.anyThing = anyThing;
    }

    //留给子类的方法
    @Override
    protected void selectPlane() {
        System.out.println("上了海航的飞机,海南航空空姐长得漂亮");
    }

    //重写钩子方法
    @Override
    protected boolean isAnyThing() {
        return this.anyThing;
    }
}

/**
 * @Author Darker
 * @Descrption
 * @Date : Created in 10:07 2020-3-13
 */
public class TakeAPlaneToShanHang extends TakeAPlane{

    private boolean anyThing = false;

    public TakeAPlaneToShanHang(boolean anyThing){
        this.anyThing = anyThing;
    }

    //留给子类的方法
    @Override
    protected void selectPlane() {
        System.out.println("上了山航的飞机,山东航空空姐身材好");
    }

    //重写钩子方法
    @Override
    protected boolean isAnyThing() {
        return this.anyThing;
    }
}

Test code:

/**
 * @Author Darker
 * @Descrption
 * @Date : Created in 10:13 2020-3-13
 */
public class TakeAPlaneTest {
    public static void main(String[] args) {
        //坐海航
        TakeAPlane haiHang = new TakeAPlaneToHaiHang(false);
        haiHang.fly();

        System.out.println("-------------------------------------------------------");
        //坐山航,但临时有事情,老婆带着小姨子跑了
        TakeAPlane shanHang = new TakeAPlaneToShanHang(true);
        shanHang.fly();
    }
}

The examples of some common logic set well, simply press book in advance subclass good process to go on it. 

 

JDBC template:

We often use the framework of some of the data layer, and only need to pass a sql parameters will return list, now that we look at this process is how specific operations.

/**
 * @Author Darker
 * @Descrption
 * @Date : Created in 10:57 2020-3-13
 */
@Data
public class User {

    private String usename;

    private String password;

    private int age;

    private String addr;
}


/**
 * @Author Darker
 * @Descrption 每行返回映射的处理方式接口
 * @Date : Created in 10:31 2020-3-13
 */
public interface RowMapper<T> {

    T mapRow(ResultSet rs, int rowNum) throws Exception;
}

/**
 * @Author Darker
 * @Descrption  jdbc模板
 * @Date : Created in 10:33 2020-3-13
 */
public abstract class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public List<?> executeQuery(String sql,RowMapper<?> rowMapper,Object[] values){

        try {
            //1.获取连接
            Connection connection = this.getConnection();
            //2.创建语句集
            PreparedStatement preparedStatement =  this.createPrePareStatement(connection,sql);
            //3.执行语句集
            ResultSet resultSet = this.executeQuery(sql,preparedStatement,values);
            //4.处理结果集
            List<?> result = this.paresResultSet(resultSet,rowMapper);
            //5.关闭结果集
            this.closeResultSet(resultSet);
            //6.关闭语句集
            this.closeStatement(preparedStatement);
            //7.关闭连接
            this.closeConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void closeConnection(Connection connection) throws Exception {
        connection.close();
    }

    protected  void closeStatement(PreparedStatement preparedStatement) throws Exception {
        preparedStatement.close();
    }

    protected  void closeResultSet(ResultSet resultSet) throws Exception {
        resultSet.close();
    }

    protected List<?> paresResultSet(ResultSet resultSet, RowMapper<?> rowMapper) throws Exception {
        List<Object> result = new ArrayList<>();
        int rowNum = 1;
        while(resultSet.next()){
            result.add(rowMapper.mapRow(resultSet,rowNum++));
        }
        return result;
    }

    protected  ResultSet executeQuery(String sql,PreparedStatement preparedStatement, Object[] values) throws Exception {
        for(int i=0,len =values.length;i<len;i++){
            preparedStatement.setObject(i,values);
        }
        return preparedStatement.executeQuery();
    }

    protected  PreparedStatement createPrePareStatement(Connection connection, String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    public Connection getConnection() throws SQLException {
            return this.dataSource.getConnection();
    }
}

/**
 * @Author Darker
 * @Descrption
 * @Date : Created in 10:58 2020-3-13
 */
public class UserDao extends JdbcTemplate {

    public UserDao(DataSource dataSource){
        super(dataSource);
    }

    public List<?> selectAll(){
        String sql = "select * from t_user";
        return super.executeQuery(sql, new RowMapper<Object>() {
            @Override
            public Object mapRow(ResultSet rs, int rowNum) throws Exception {
                User user = new User();
                //字段过多,可以用原型模式优化
                user.setUsename(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAge(rs.getInt("age"));
                user.setAddr(rs.getString("addr"));
                return user;
            }
        },null);
    }

}

/**
 * @Author Darker
 * @Descrption
 * @Date : Created in 11:11 2020-3-13
 */
public class UserDaoTest {
    public static void main(String[] args) {
        //有兴趣的小伙伴可以自己去测试一下,这里我就懒得去拿数据源了
        UserDao userDao = new UserDao(null);
        List<?> result = userDao.selectAll();
        System.out.println(result);

    }
}

 

Source Application:

jdk source code where the use of a template pattern here?

The answer is that we use the longest AbstractList, we find it's get a look at methods.

Take a look at its implementation subclasses abstract get method to see if there is any difference, the first one is ArrayList

 

It is the first index to check, and then extract the elements, and then look ArrayQueue

 

 

Obviously, it has to be modulo the capacity, operation value again, but they have a lot of public methods, which is very typical of the template pattern.

Let's look at HttpServlet we are using every day.

It is the most logical processing of the request are written, leaving two methods to achieve sub-class, let's look at why it can be identified get, post method. 

 

 Skip to the common logic inside it has been written, right, this is a typical pattern template.

Continue to see mybatis framework we often use

 

It left some of the methods of operation to us, such as updating and inquiry, its sub-class implementation is not the same, there is little interest in the partnership can look at themselves.

 

 

to sum up:

advantage: 

1. improve the reusability of code

2. Improve the scalability of the code

3. comply with the principle of opening and closing

Disadvantages:

1. The increase in the number of class

2. insight increases the complexity of system implementation

3. The inheritance their own shortcomings, if the parent class adds new abstract method, all subclasses must change

Published 27 original articles · won praise 1 · views 3640

Guess you like

Origin blog.csdn.net/qq_40111437/article/details/104834122