模板方法 & spring jdbcTemplate 的应用

本文探讨了模板方法设计模式在Office文件转换为PDF过程中的应用,通过抽象类定义固定步骤,子类实现具体操作。同时,介绍了JDBC模板模式简化数据库操作,避免重复代码,提高开发效率。
简要介绍

工作中遇到一个问题,就是office 转pdf ,office 有 ppt,excel,word,viso 文件类型,不同的文件类型,有不同的转码方法,但是步骤都是一样的,都是要检查授权文件,然后设置字体目录,最后转码,此时就可以用到模板方法的设计模式。

在这里插入图片描述

代码示例:

父类

package com.bosssoft.bigdata.form.template;

import java.io.File;

public abstract class AbstractPDFConverter {

    protected abstract void matchFileType(String fileName);


    protected abstract void matchLicense();


    protected abstract void convert2PDF(File sourceFile,File targetFile);


    private void setDefualtFontDir(){
        System.out.println("设置字体目录");
    }


    public void conver(File sourceFile, File targetFile){
        //检查文件类型
        this.matchFileType("文件名称");
        //检查转码证书
        this.matchLicense();
        //设置字体目录
        this.setDefualtFontDir();
        //转码
        this.convert2PDF(sourceFile,targetFile);
    }

}

子类

package com.bosssoft.bigdata.form.template;

import java.io.File;

public class PPTConvert extends AbstractPDFConverter {

    @Override
    protected void matchFileType(String fileName) {
        //匹配数据类型
        System.out.println("ppt数据类型");
    }

    @Override
    protected void matchLicense() {
        //匹配证书
        System.out.println("ppt证书匹配");
    }

    @Override
    protected void convert2PDF(File sourceFile, File targetFile) {
        //文件转码
        System.out.println("ppt文件转码");

    }
}

子类

package com.bosssoft.bigdata.form.template;

import java.io.File;

public class EXCELConvert extends AbstractPDFConverter {

    @Override
    protected void matchFileType(String fileName) {
        //匹配数据类型
        System.out.println("EXCEL数据类型");
    }

    @Override
    protected void matchLicense() {
         //匹配证书
        System.out.println("EXCEL证书匹配");
    }

    @Override
    protected void convert2PDF(File sourceFile, File targetFile) {
           //文件转码
        System.out.println("EXCEL文件转码");
    }
}

package com.bosssoft.bigdata.form.template;

public class Client {

    public static void main(String[] args) {
        AbstractPDFConverter pptConvert = new PPTConvert();
        pptConvert.conver(null,null);

        AbstractPDFConverter excelConvert = new EXCELConvert();
        excelConvert.conver(null,null);
    }
}

在这里插入图片描述

小结

模板方法目前是最简单的也是最常用的一种设计模式,当多个子类有公有的方法,且基本处理逻辑与流程能通用时,就可以使用

spring jdbcTemplate的应用

网上看到一个示例,十几年前的一个论坛上的
地址:https://www.iteye.com/topic/119485
讲得很清晰易懂

package com.dongguoh;  
  
import java.sql.*;  
/* 
 * 用匿名类的方式去运用这个接口 
 */  
public interface IStatementCallback {  
    public Object doInStatement(Statement stmt) throws RuntimeException,SQLException;  
      
}  
  
2.而这里是最关键的,就是建一个Jdbc的模板方法,把那些经常要做的try{} catch{}都写在一个类里  
    免得以后每次都还去写。这就成啦代码复用.  
  
package com.dongguoh;  
  
import java.sql.*;  
/* 
 * 在这里我就不用Spring的注入啦,直接写个完整的 
 * 如果不会Spring的,也同样的像使用Spring中的JdbcTemplate类一样的使用. 
 * 如果你看过Spring的书,那么这个例子也是一个Spring的入门jdbc的好例子 
 *  
 * 而在这里我们的这个JdbcTemplate就成啦一个通用的方法,以后我们要SQL语句连接数据库的 
 * 时候不用每次都去写try{}catch{}啦,老那样写真的很烦,一次性就把它搞定啦 
 */  
public class JdbcTemplate {  
      
  
    public Object execute(IStatementCallback action) {  
        Connection conn = null;  
        Statement stmt = null;  
        Object result = null;         
        try {  
            conn=this.getConnection();  
            conn.setAutoCommit(false);            
            stmt=conn.createStatement();  
              
            //注意这一句  
            result=action.doInStatement(stmt);  
              
            conn.commit();  
            conn.setAutoCommit(true);             
        } catch (SQLException e) {  
            transactionRollback(conn);//进行事务回滚  
            e.printStackTrace();  
            throw new RuntimeException(e);  
        }finally{  
            this.closeStatement(stmt);  
            this.closeConnection(conn);  
        }  
  
        return result;  
    }  
      
    /* 
     * 当发生异常时进行事务回滚 
     */  
    private void transactionRollback(Connection conn){  
        if(conn!=null){  
            try {  
                conn.rollback();  
            } catch (SQLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
          
    }  
    //关闭打开的Statement  
    private void closeStatement(Statement stmt){  
        if(stmt!=null){  
            try {  
                stmt.close();  
                stmt=null;  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
    //关闭打开的Connection   
    private void closeConnection(Connection conn){  
        if(conn!=null){  
            try {  
                conn.close();  
                conn=null;  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    //取得一个Connction  
    private Connection getConnection() {          
        String driver = "com.mysql.jdbc.Driver";  
        String url = "jdbc:mysql://127.0.0.1/Hibernate";          
        Connection conn=null;  
        try {  
            Class.forName(driver);  
            conn = DriverManager.getConnection(url, "root", "dongguoh");  
        } catch (ClassNotFoundException e) {  
            e.printStackTrace();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
        return conn;  
    }  
  
}  
package com.dongguoh;  
  
import java.sql.*;  
  
import junit.framework.TestCase;  
  
public class TestTemplate extends TestCase {  
  
    public void testJdbcTemplate(){  
        JdbcTemplate jt=new JdbcTemplate();  
        /* 
         * 因为IStatementCallback是一个接口,所以我们在这里直接用一个匿名类来实现 
         * 如果已经正确的插入啦一条数据的话 ,它会正确的返回一个 整数 1  
         * 而我们这里的stmt是从JdbcTemplate中传过来的 
         */  
        int count=(Integer)jt.execute(new IStatementCallback(){  
            public Object doInStatement(Statement stmt) throws RuntimeException, SQLException {  
  
                String sql="INSERT INTO person VALUES(1,'dongguoh','123456')";  
                int result=stmt.executeUpdate(sql);  
                return new Integer(result);  
            }             
        });       
        System.out.println("Count: "+count);  
          
        /* 
         * 在这里我们就把刚刚插入的数据取出一个数据,直接输出来 
         *  
         */  
        jt.execute(new IStatementCallback(){  
            public Object doInStatement(Statement stmt) throws RuntimeException, SQLException {  
  
                String sql="SELECT name,password FROM person WHERE id=1";  
                ResultSet rs=null;  
                rs=stmt.executeQuery(sql);  
                if(rs.next()){  
                    System.out.println(rs.getString("name"));  
                    System.out.println(rs.getString("password"));  
                }  
                /* 
                 * 在这里就直接返回一个1啦,如果你愿意的话,你可以再写一个Person类 
                 * 在if语句中实例化它,赋值再把它返回 
                 */  
                return new Integer(1);  
            }             
        });       
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值