1 自定义MyBatis框架的分析
1.1 涉及知识点介绍
本章我们将使用前面所学的基础知识来构建一个属于自己的持久层框架,将会涉及到的一些知识点:工厂模式(Factory工厂模式)、构造者模式(Builder模式)、代理模式、反射、自定义注解、注解的反射、xml解析、数据库元数据、元数据的反射等。
1.2 分析流程
2 前期准备
2.1 创建Maven工程
创建mybatis02的工程,工程信息如下:
<groupId>com.itheima</groupId>
<artifactId>mybatis02</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
2.2 引入相关坐标
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
2.3 引入工具类到项目中
-
XMLConfigBuilder类:用于解析配置文件
package com.itheima.mybatis.utils; //import com.itheima.mybatis.annotations.Select; import com.itheima.mybatis.annotations.Select; import com.itheima.mybatis.cfg.Configuration; import com.itheima.mybatis.cfg.Mapper; import com.itheima.mybatis.io.Resources; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author 黑马程序员 * @Company http://www.ithiema.com * 用于解析配置文件 */ public class XMLConfigBuilder { /** * 解析主配置文件,把里面的内容填充到DefaultSqlSession所需要的地方 * 使用的技术: * dom4j+xpath */ public static Configuration loadConfiguration(InputStream config) { try { //定义封装连接信息的配置对象(mybatis的配置对象) Configuration cfg = new Configuration(); //1.获取SAXReader对象 SAXReader reader = new SAXReader(); //2.根据字节输入流获取Document对象 Document document = reader.read(config); //3.获取根节点 Element root = document.getRootElement(); //4.使用xpath中选择指定节点的方式,获取所有property节点 List<Element> propertyElements = root.selectNodes("//property"); //5.遍历节点 for (Element propertyElement : propertyElements) { //判断节点是连接数据库的哪部分信息 //取出name属性的值 String name = propertyElement.attributeValue("name"); if ("driver".equals(name)) { //表示驱动 //获取property标签value属性的值 String driver = propertyElement.attributeValue("value"); cfg.setDriver(driver); } if ("url".equals(name)) { //表示连接字符串 //获取property标签value属性的值 String url = propertyElement.attributeValue("value"); cfg.setUrl(url); } if ("username".equals(name)) { //表示用户名 //获取property标签value属性的值 String username = propertyElement.attributeValue("value"); cfg.setUsername(username); } if ("password".equals(name)) { //表示密码 //获取property标签value属性的值 String password = propertyElement.attributeValue("value"); cfg.setPassword(password); } } //取出mappers中的所有mapper标签,判断他们使用了resource还是class属性 List<Element> mapperElements = root.selectNodes("//mappers/mapper"); //遍历集合 for (Element mapperElement : mapperElements) { //判断mapperElement使用的是哪个属性 Attribute attribute = mapperElement.attribute("resource"); if (attribute != null) { System.out.println("使用的是XML"); //表示有resource属性,用的是XML //取出属性的值 String mapperPath = attribute.getValue();//获取属性的值"com/itheima/dao/IUserDao.xml" //把映射配置文件的内容获取出来,封装成一个map Map<String, Mapper> mappers = loadMapperConfiguration(mapperPath); //给configuration中的mappers赋值 cfg.setMappers(mappers); } else { System.out.println("使用的是注解"); //表示没有resource属性,用的是注解 //获取class属性的值 String daoClassPath = mapperElement.attributeValue("class"); //根据daoClassPath获取封装的必要信息 Map<String, Mapper> mappers = loadMapperAnnotation(daoClassPath); //给configuration中的mappers赋值 cfg.setMappers(mappers); } } //返回Configuration return cfg; } catch (Exception e) { throw new RuntimeException(e); } finally { try { config.close(); } catch (Exception e) { e.printStackTrace(); } } } /** * 根据传入的参数,解析XML,并且封装到Map中 * * @param mapperPath 映射配置文件的位置 * @return map中包含了获取的唯一标识(key是由dao的全限定类名和方法名组成) * 以及执行所需的必要信息(value是一个Mapper对象,里面存放的是执行的SQL语句和要封装的实体类全限定类名) */ private static Map<String, Mapper> loadMapperConfiguration(String mapperPath) throws IOException { InputStream in = null; try { //定义返回值对象 Map<String, Mapper> mappers = new HashMap<String, Mapper>(); //1.根据路径获取字节输入流 in = Resources.getResourceAsStream(mapperPath); //2.根据字节输入流获取Document对象 SAXReader reader = new SAXReader(); Document document = reader.read(in); //3.获取根节点 Element root = document.getRootElement(); //4.获取根节点的namespace属性取值 String namespace = root.attributeValue("namespace");//是组成map中key的部分 //5.获取所有的select节点 List<Element> selectElements = root.selectNodes("//select"); //6.遍历select节点集合 for (Element selectElement : selectElements) { //取出id属性的值 组成map中key的部分 String id = selectElement.attributeValue("id"); //取出resultType属性的值 组成map中value的部分 String resultType = selectElement.attributeValue("resultType"); //取出文本内容 组成map中value的部分 String queryString = selectElement.getText(); //创建Key String key = namespace + "." + id; //创建Value Mapper mapper = new Mapper(); mapper.setQueryString(queryString); mapper.setResultType(resultType); //把key和value存入mappers中 mappers.put(key, mapper); } return mappers; } catch (Exception e) { throw new RuntimeException(e); } finally { in.close(); } } /** * 根据传入的参数,得到dao中所有被select注解标注的方法。 * 根据方法名称和类名,以及方法上注解value属性的值,组成Mapper的必要信息 * * @param daoClassPath * @return */ private static Map<String, Mapper> loadMapperAnnotation(String daoClassPath) throws Exception { //定义返回值对象 Map<String, Mapper> mappers = new HashMap<String, Mapper>(); //1.得到dao接口的字节码对象 Class daoClass = Class.forName(daoClassPath); //2.得到dao接口中的方法数组 Method[] methods = daoClass.getMethods(); //3.遍历Method数组 for (Method method : methods) { //取出每一个方法,判断是否有select注解 boolean isAnnotated = method.isAnnotationPresent(Select.class); if (isAnnotated) { //创建Mapper对象 Mapper mapper = new Mapper(); //取出注解的value属性值 Select selectAnno = method.getAnnotation(Select.class); String queryString = selectAnno.value(); mapper.setQueryString(queryString); //获取当前方法的返回值,还要求必须带有泛型信息 Type type = method.getGenericReturnType();//List<User> //判断type是不是参数化的类型 if (type instanceof ParameterizedType) { //强转 ParameterizedType ptype = (ParameterizedType) type; //得到参数化类型中的实际类型参数 Type[] types = ptype.getActualTypeArguments(); //取出第一个 Class domainClass = (Class) types[0]; //获取domainClass的类名 String resultType = domainClass.getName(); //给Mapper赋值 mapper.setResultType(resultType); } //组装key的信息 //获取方法的名称 String methodName = method.getName(); String className = method.getDeclaringClass().getName(); String key = className + "." + methodName; //给map赋值 mappers.put(key, mapper); } } return mappers; } }
-
Executor类:负责执行SQL语句,并且封装结果集
package com.itheima.mybatis.utils; import com.itheima.mybatis.cfg.Mapper; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.List; /** * @author 黑马程序员 * @Company http://www.ithiema.com * 负责执行SQL语句,并且封装结果集 */ public class Executor { public <E> List<E> selectList(Mapper mapper, Connection conn) { PreparedStatement pstm = null; ResultSet rs = null; try { //1.取出mapper中的数据 String queryString = mapper.getQueryString();//select * from user String resultType = mapper.getResultType();//com.itheima.domain.User Class domainClass = Class.forName(resultType); //2.获取PreparedStatement对象 pstm = conn.prepareStatement(queryString); //3.执行SQL语句,获取结果集 rs = pstm.executeQuery(); //4.封装结果集 List<E> list = new ArrayList<E>();//定义返回值 while (rs.next()) { //实例化要封装的实体类对象 E obj = (E) domainClass.newInstance(); //取出结果集的元信息:ResultSetMetaData ResultSetMetaData rsmd = rs.getMetaData(); //取出总列数 int columnCount = rsmd.getColumnCount(); //遍历总列数 for (int i = 1; i <= columnCount; i++) { //获取每列的名称,列名的序号是从1开始的 String columnName = rsmd.getColumnName(i); //根据得到列名,获取每列的值 Object columnValue = rs.getObject(columnName); //给obj赋值:使用Java内省机制(借助PropertyDescriptor实现属性的封装) PropertyDescriptor pd = new PropertyDescriptor(columnName, domainClass);//要求:实体类的属性和数据库表的列名保持一种 //获取它的写入方法 Method writeMethod = pd.getWriteMethod(); //把获取的列的值,给对象赋值 writeMethod.invoke(obj, columnValue); } //把赋好值的对象加入到集合中 list.add(obj); } return list; } catch (Exception e) { throw new RuntimeException(e); } finally { release(pstm, rs); } } private void release(PreparedStatement pstm, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } if (pstm != null) { try { pstm.close(); } catch (Exception e) { e.printStackTrace(); } } } }
-
DataSourceUtil类:用于创建数据源的工具类
package com.itheima.mybatis.utils; import com.itheima.mybatis.cfg.Configuration; import java.sql.Connection; import java.sql.DriverManager; /** * @author 黑马程序员 * @Company http://www.ithiema.com * 用于创建数据源的工具类 */ public class DataSourceUtil { /** * 用于获取一个连接 * * @param cfg * @return */ public static Connection getConnection(Configuration cfg) { try { Class.forName(cfg.getDriver()); return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword()); } catch (Exception e) { throw new RuntimeException(e); } } }
2.4 编写SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" ></property>
<property name="url" value="jdbc:mysql:///eesy" ></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</dataSource>
</environment>
</environments>
</configuration>
注意: 此处我们直接使用的是mybatis的配置文件,但是由于我们没有使用mybatis的jar包,所以要把配置文件的约束删掉否则会报错(如果电脑能接入互联网,不删也行)
2.5 编写读取配置文件类
package com.itheima.mybatis.io;
import java.io.InputStream;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 使用类加载器读取配置文件的类
*/
public class Resources {
/**
* 根据传入的参数,获取一个字节输入流
* 在实际开发中读取配置文件:
* 第一:使用类加载器。但是有要求:
* a文件不能过大
* b文件必须在类路径下(classpath)
* 第二:使用ServletContext的getRealPath()
*
* @param filePath
* @return
*/
public static InputStream getResourceAsStream(String xmlPath) {
return Resources.class.getClassLoader().getResourceAsStream(xmlPath);
}
}
2.6 编写Mapper类
package com.itheima.mybatis.cfg;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 用于封装执行的SQL语句和结果类型的全限定类名
*/
public class Mapper {
private String queryString;//SQL
private String resultType;//实体类的全限定类名
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
}
2.7 编写Configuration配置类
package com.itheima.mybatis.cfg;
import java.util.HashMap;
import java.util.Map;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 自定义mybatis的配置类
*/
public class Configuration {
private String driver;
private String url;
private String username;
private String password;
private Map<String, Mapper> mappers = new HashMap<String, Mapper>();
public Map<String, Mapper> getMappers() {
return mappers;
}
public void setMappers(Map<String, Mapper> mappers) {
this.mappers.putAll(mappers);//此处需要使用追加的方式
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2.8 编写User实体类
package com.itheima.domain;
import java.io.Serializable;
import java.util.Date;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
3 基于XML的自定义MyBatis框架
3.1 编写持久层接口和IUserDao.xml
package com.itheima.dao;
import com.itheima.domain.User;
import com.itheima.mybatis.annotations.Select;
import java.util.List;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 用户的持久层接口
*/
public interface IUserDao {
/**
* 查询所有操作
*
* @return
*/
List<User> findAll();
}
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="com.itheima.dao.IUserDao">
<!--配置查询所有-->
<select id="findAll" resultType="com.itheima.domain.User">
select * from user
</select>
</mapper>
注意:此处我们使用的也是mybatis的配置文件,所以也要把约束删除了
3.2 编写构建者类
package com.itheima.mybatis.sqlsession;
import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.sqlsession.defaults.DefaultSqlSessionFactory;
import com.itheima.mybatis.utils.XMLConfigBuilder;
import java.io.InputStream;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 用于创建一个SqlSessionFactory对象
*/
public class SqlSessionFactoryBuilder {
/**
* 根据参数的字节输入流来构建一个SqlSessionFactory工厂
*
* @param config
* @return
*/
public SqlSessionFactory build(InputStream in) {
Configuration cfg = XMLConfigBuilder.loadConfiguration(in);
return new DefaultSqlSessionFactory(cfg);
}
}
3.3 编写SqlSessionFactory接口和实现类
package com.itheima.mybatis.sqlsession;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public interface SqlSessionFactory {
/**
* 用于打开一个新的SqlSession对象
*
* @return
*/
SqlSession openSession();
}
package com.itheima.mybatis.sqlsession.defaults;
import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.sqlsession.SqlSession;
import com.itheima.mybatis.sqlsession.SqlSessionFactory;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* SqlSessionFactory接口的实现类
*/
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private Configuration cfg;
public DefaultSqlSessionFactory(Configuration cfg) {
this.cfg = cfg;
}
/**
* 用于创建一个新的操作数据库对象
*
* @return
*/
@Override
public SqlSession openSession() {
return new DefaultSqlSession(cfg);
}
}
3.4 编写SqlSession接口和实现类
package com.itheima.mybatis.sqlsession;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 自定义Mybatis中和数据库交互的核心类
* 它里面可以创建dao接口的代理对象
*/
public interface SqlSession {
/**
* 根据参数创建一个代理对象
*
* @param daoInterfaceClass dao的接口字节码
* @param <T>
* @return
*/
<T> T getMapper(Class<T> daoInterfaceClass);
/**
* 释放资源
*/
void close();
}
package com.itheima.mybatis.sqlsession.defaults;
import com.itheima.mybatis.cfg.Configuration;
import com.itheima.mybatis.sqlsession.SqlSession;
import com.itheima.mybatis.sqlsession.proxy.MapperProxy;
import com.itheima.mybatis.utils.DataSourceUtil;
import java.lang.reflect.Proxy;
import java.sql.Connection;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* SqlSession接口的实现类
*/
public class DefaultSqlSession implements SqlSession {
private Configuration cfg;
private Connection connection;
public DefaultSqlSession(Configuration cfg) {
this.cfg = cfg;
connection = DataSourceUtil.getConnection(cfg);
}
/**
* 用于创建代理对象
*
* @param daoInterfaceClass dao的接口字节码
* @param <T>
* @return
*/
@Override
public <T> T getMapper(Class<T> daoInterfaceClass) {
return (T) Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),
new Class[]{daoInterfaceClass}, new MapperProxy(cfg.getMappers(), connection));
}
/**
* 用于释放资源
*/
@Override
public void close() {
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3.5 编写用于创建Dao接口代理对象的类
package com.itheima.mybatis.sqlsession.proxy;
import com.itheima.mybatis.cfg.Mapper;
import com.itheima.mybatis.utils.Executor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public class MapperProxy implements InvocationHandler {
//map的key是全限定类名+方法名
private Map<String, Mapper> mappers;
private Connection conn;
public MapperProxy(Map<String, Mapper> mappers, Connection conn) {
this.mappers = mappers;
this.conn = conn;
}
/**
* 用于对方法进行增强的,我们的增强其实就是调用selectList方法
*
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//1.获取方法名
String methodName = method.getName();
//2.获取方法所在类的名称
String className = method.getDeclaringClass().getName();
//3.组合key
String key = className + "." + methodName;
//4.获取mappers中的Mapper对象
Mapper mapper = mappers.get(key);
//5.判断是否有mapper
if (mapper == null) {
throw new IllegalArgumentException("传入的参数有误");
}
//6.调用工具类执行查询所有
return new Executor().selectList(mapper, conn);
}
}
3.6 运行测试类
package com.itheima.test;
import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import com.itheima.mybatis.io.Resources;
import com.itheima.mybatis.sqlsession.SqlSession;
import com.itheima.mybatis.sqlsession.SqlSessionFactory;
import com.itheima.mybatis.sqlsession.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* mybatis的入门案例
*/
public class MybatisTest {
/**
* 入门案例
*
* @param args
*/
public static void main(String[] args) throws Exception {
//1.读取配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3.使用工厂生产SqlSession对象
SqlSession session = factory.openSession();
//4.使用SqlSession创建Dao接口的代理对象
IUserDao userDao = session.getMapper(IUserDao.class);
//5.使用代理对象执行方法
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println(user);
}
//6.释放资源
session.close();
in.close();
}
}
4 基于注解方式定义MyBatis框架
4.1 自定义@Select注解
package com.itheima.mybatis.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* 查询的注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select {
/**
* 配置SQL语句的
*
* @return
*/
String value();
}
4.2 修改持久层接口
package com.itheima.dao;
import com.itheima.domain.User;
import com.itheima.mybatis.annotations.Select;
import java.util.List;
/**
* @author 黑马程序员
* @Company http://www.ithiema.com
* <p>
* 用户的持久层接口
*/
public interface IUserDao {
/**
* 查询所有操作
*
* @return
*/
@Select("select * from user")
List<User> findAll();
}
4.3 修改SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- mybatis的主配置文件 -->
<configuration>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境-->
<environment id="mysql">
<!-- 配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<!--<mapper resource="com/itheima/dao/IUserDao.xml"/>-->
<mapper class="com.itheima.dao.IUserDao"/>
</mappers>
</configuration>
5 自定义MyBatis的设计模式说明
5.1 工厂模式(SqlSessionFactory)
工厂模式的原理如下图:
5.2 代理模式(MapperProxyFactory)
代理模式分为静态和动态代理:静态代理,我们通常都很熟悉。有一个写好的代理类,实现与要代理的类的一个共同的接口,目的是为了约束也为了安全。具体不再多说。 这里主要想说的是关于动态代理。我们知道静态代理若想代理多个类,实现扩展功能,那么它必须具有多个代理类分别取代理不同的实现类。这样做的后果是造成太多的代码冗余。那么我们会思考如果做,才能既满足需求,又没有太多的冗余代码呢?——————动态代理。通过前面的课程我们已经学过了基于JDK的动态代理实现方式,今天我们就会使用JDK动态代理方式来编写MapperProxyFactory类。
动态代理模型图:
5.3 构建者模式(SqlSessionFactoryBuilder)
具体设计模式的模型图如下:
从图中我们可以看出,创建者模式由四部分组成。
- 抽象创建者角色:给出一个抽象接口,以规范产品对象的各个组成成分的建造。一般而言,此接口独立于应用程序的商业逻辑。模式中直接创建产品对象的是具体创建者角色。具体创建者必须实现这个接口的两种方法:一是建造方法,比如图中的buildPart1和buildPart2方法;另一种是结果返回方法,即图中的getProduct方法。一般来说,产品所包含的零件数目与建造方法的数目相符。换言之,有多少零件,就有多少相应的建造方法。
- 具体创建者角色:他们在应用程序中负责创建产品的实例。这个角色要完成的任务包括: 1、实现抽象创建者所声明的抽象方法,给出一步一步的完成产品创建实例的操作。 2、在创建完成后,提供产品的实例。
- 导演者角色:这个类调用具体创建者角色以创建产品对象。但是导演者并没有产品类的具体知识,真正拥有产品类的具体知识的是具体创建者角色。
- 产品角色:产品便是建造中的复杂对象。一般说来,一个系统中会有多于一个的产品类,而且这些产品类并不一定有共同的接口,而完全可以使不相关联的。
5.4 小结
通过自定义MyBatis框架的学习,我们将前面的基础知识很好的结合在一起,并且强化了我们的设计模式及使用。希望大家能够抽时间多练习,这也是系统架构师的必由之路。