设计模式 – 模板设计模式

news/2024/7/18 8:40:57

模板设计模式

模板方法模式(Template Method Pattern),又叫模板模式(Template Pattern),在一个抽象类公开定义了执行它的方法的模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。

该模式的主要优点如下。
1) 它封装了不变部分,扩展可变部分。它把认为是不变部分的算法封装到父类中实现,而把可变部分算法由子类继承实现,便于子类继续扩展。
2) 它在父类中提取了公共的部分代码,便于代码复用。
3) 部分方法是由子类实现的,因此子类可以通过扩展方式增加相应的功能,符合开闭原则。

案例

JdbcTemplate uml 图:
在这里插入图片描述

1 pom

 <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>

    </dependencies>

2 JdbcFactory

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class JdbcFactory {

    /**
     * ###########################DB配置########################
     */
    private static final String URL = "jdbc:mysql://localhost:3306/test?charset=utf8mb4&serverTimezone=UTC&useUnicode=true&useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final String DRIVER = "com.mysql.jdbc.Driver";


    private static DataSource db;

    static {

        Map<String, String> map = new HashMap<>();
        map.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, DRIVER);
        map.put(DruidDataSourceFactory.PROP_URL, URL);
        map.put(DruidDataSourceFactory.PROP_USERNAME, USERNAME);
        map.put(DruidDataSourceFactory.PROP_PASSWORD, PASSWORD);
        try {
            db = DruidDataSourceFactory.createDataSource(map);
        } catch (Exception e) {
            db = null;
            e.printStackTrace();
        }

    }

    private JdbcFactory() {

    }


    public static DataSource getInstance() {
        return db;
    }


}

3 RowMapper


/**
 * ORM 定制化接口
 */
public interface RowMapper<T> {

    T mapRow(ResultSet rs, int rowNum) throws SQLException;

}


4 JdbcTemplate

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public abstract class JdbcTemplate {


    private DataSource dataSource;

    public JdbcTemplate(DataSource dateSource) {

        this.dataSource = dateSource;
    }


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

        try {
            //1 获取连接
            Connection connection = this.getConnection();
            //2 创建语句集
            PreparedStatement pstm = this.createPrepareStatement(connection, sql);
            //3 执行语句集
            ResultSet rs = execute(pstm, values);
            //4 处理结果集
            List<T> list = paresResultSet(rs, rowMapper);
            //5 关闭结果集
            this.closeResultSet(rs);
            //6 关闭语句集
            this.closeStatement(pstm);
            //7 关闭连接
            this.closeConnection(connection);
            //8 返回
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return new ArrayList<>();
    }

    protected void closeConnection(Connection connection) throws SQLException {

        if (connection != null) {
            connection.close();
        }

    }

    protected void closeStatement(PreparedStatement pstm) throws SQLException {
        pstm.close();
    }


    protected void closeResultSet(ResultSet rs) throws SQLException {
        rs.close();
    }

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

    }

    private ResultSet execute(PreparedStatement pstm, Object[] values) throws SQLException {

        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                pstm.setObject(i, values[i]);
            }
        }
        return pstm.executeQuery();
    }

    protected PreparedStatement createPrepareStatement(Connection connection, String sql) throws SQLException {


        return connection.prepareStatement(sql);

    }

    private Connection getConnection() throws SQLException {

        return this.dataSource.getConnection();
    }


}

5 业务类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {

    private Integer id;

    private String name;

    private Integer age;


}



public class StudentDao extends JdbcTemplate {

    public StudentDao(DataSource dateSource) {
        super(dateSource);
    }


    public List<Student> selectAll() {
        String sql = "select * from t_student";
        return super.executeQuery(sql, (rs, rowNum) -> {
            Student student = new Student();
            student.setId(rs.getInt("id"));
            student.setAge(rs.getInt("age"));
            student.setName(rs.getString("name"));
            return student;
        }, null);

    }


}


6 测试

public class JdbcTest {


    public static void main(String[] args) throws Exception {

        DataSource instance = JdbcFactory.getInstance();
        StudentDao studentDao=new StudentDao(instance);
        List<Student> students = studentDao.selectAll();
        System.out.println(students.toString());


    }

}

在这里插入图片描述


http://www.niftyadmin.cn/n/4556696.html

相关文章

关于C语言initgraph图象函数

参考资料&#xff1a;http://course.cug.edu.cn/cugFirst/Adv_program/C_ziliao/ctuxin1.htm 答案补充 是的 若没有驱动程序 当程序进行到intitgraph()语句时 在编译和链接时并没有将相应的驱动程序(*.BGI)装入到执行程序 都这个年代了 现在根本就不用 还用它编过几个挺成样的软…

设计模式 – 适配器模式

1 介绍 适配器模式(Adapter Pattern)将某个类的接口转换成客户端期望的另一个接口表示&#xff0c;主要目的是兼容性&#xff0c;将一个类的接口转换成客户希望的另外一个接口&#xff0c;使得原本由于接口不兼容而不能一起工作的那些类能一起工作 目的&#xff1a;让原本接口…

C语言编辑进

PS&#xff1a;如果代码有问题 最后执行 然后build *.exe 那就在最上边工具条里点build->compile *.c 勾选buildminibar就会有上边那个工具条了如果还没找到 那在上边右键 执行如果没有 停止连接 连接 重新下个 在上边工具栏上有一排6个工具&#xff1a;编译 最后所产生的.e…

设计模式 – 装饰者模式

概念 (1) 装饰&#xff08;Decorator&#xff09;模式的定义&#xff1a;指在不改变现有对象结构的情况下&#xff0c;动态地给该对象增加一些职责&#xff08;即增加其额外功能&#xff09;的模式&#xff0c;它属于对象结构型模式。 (2) 装饰&#xff08;Decorator&#xf…

设计模式 – 观察者模式

概念 1、观察者&#xff08;Observer&#xff09;模式的定义&#xff1a;指多个对象间存在一对多的依赖关系&#xff0c;当一个对象的状态发生改变时&#xff0c;所有依赖于它的对象都得到通知并被自动更新。这种模式有时又称作发布-订阅模式、模型-视图模式&#xff0c;它是对…

c++类和对象等编程

仅供参考 另外我的程序可能有错误 你如果高兴的话 可以在构造函数中初始变量什么的 这个只是我个人意见 #include <iostream>#include <string>using namespace std;class rech{public: std::int long0; std::int wide0;}把这个存放在rech.h中#include <iostrea…

在SQL中怎么删除一列的语法是什么

你试一下 A B C1 b1 c12 b2 c2delete from test where A ‘1’ delete from test where A ‘&#xff08;你要删除列的主键字段的值&#xff09;’ 答案补充 不好意思哦 假设表test中 A列位主键字段 &#xff09; ||| Alter table test Drop column B(语法是&#xff1a;Alter …

手写简易版SpringIoc、SpringMvc

1 工程目录 2 pom <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</ar…