C03 抽象工厂 JDK源码分析

本文探讨了Java中SQL Connection接口如何运用抽象工厂模式,创建Statement和PreparedStatement对象。通过具体工厂实现,如com.mysql.jdbc.ConnectionImpl,为MySQL数据库提供特定的StatementImpl和ServerPreparedStatement实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.sql.Connection

  • 接口java.sql.Connection相当于抽象工厂CourseFactory,定义了一个产品族会生产哪些产品;
  • 抽象方法的返回值java.sql.Statement和java.sql.PreparedStatement相当于定义了2个产品等级结构,对应Video和Article;
  • java.sql.Statement和java.sql.PreparedStatement也是接口;
  • com.mysql.jdbc.ConnectionImpl是一个具体工厂,生产产品族MySQL的产品,其中生产的com.mysql.jdbc.StatementImpl和com.mysql.jdbc.ServerPreparedStatement是具体产品,都属于MySQL产品族;

抽象工厂

  • java.sql.Connection;
public interface Connection  extends Wrapper, AutoCloseable {
    Statement createStatement() throws SQLException;
    PreparedStatement prepareStatement(String sql) throws SQLException;
}

2个产品等级结构

  • java.sql.Statement;
  • java.sql.PreparedStatement;
public interface Statement extends Wrapper, AutoCloseable {...}
public interface PreparedStatement extends Statement {...}

具体工厂

  • com.mysql.jdbc.ConnectionImpl生产MySQL产品族的产品;
package com.mysql.jdbc;
public class ConnectionImpl extends ConnectionPropertiesImpl implements MySQLConnection {
    public java.sql.Statement createStatement() throws SQLException {
        return createStatement(DEFAULT_RESULT_SET_TYPE, DEFAULT_RESULT_SET_CONCURRENCY);
    }
    public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException {
        return prepareStatement(sql, DEFAULT_RESULT_SET_TYPE, DEFAULT_RESULT_SET_CONCURRENCY);
    }
}

具体产品

  • com.mysql.jdbc.StatementImpl;
  • com.mysql.jdbc.ServerPreparedStatement;
package com.mysql.jdbc;
public class StatementImpl implements Statement {...}
public class ServerPreparedStatement extends PreparedStatement {...}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值