设计模式 构造器模式
构造器模式使用多个简单的对象一步一步构建成一个复杂的对象。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式,常见于在构建一个复杂的对象,里面可能包含一些业务逻辑,比如检查,属性转换等。如果都在客户端手动去设置,那么会产生大量的冗余代码。那么这时候,就可以考虑使用构造器模式。
比如,在MyBatis中,MappedStatement的创建过程就使用了构造器模式。
XML文件中的每一个SQL标签就要生成一个MappedStatement对象,它里面包含很多个属性,构造的对象也是它。
public final class MappedStatement {private String resource;private Configuration configuration;private String id;private SqlSource sqlSource;private ParameterMap parameterMap;private List<ResultMap> resultMaps;//.....省略大部分属性}
然后有一个内部类Builder,它负责完成MappedStatement对象的构造。
首先,这个Builder类,通过默认的构造函数,先完成对MappedStatement对象,部分的构造。
public static class Builder {private MappedStatement mappedStatement = new MappedStatement();public Builder(Configuration configuration, String id, SqlSource sqlSource, SqlCommandType sqlCommandType) {mappedStatement.configuration = configuration;mappedStatement.id = id;mappedStatement.sqlSource = sqlSource;mappedStatement.statementType = StatementType.PREPARED;mappedStatement.resultSetType = ResultSetType.DEFAULT;//.....省略大部分过程}}
然后,通过一系列方法,可以设置特定的属性,并返回这个Builder类,这里的方法适合处理一些业务逻辑。
public static class Builder {public Builder parameterMap(ParameterMap parameterMap) {mappedStatement.parameterMap = parameterMap;return this;}public Builder resultMaps(List<ResultMap> resultMaps) {mappedStatement.resultMaps = resultMaps;for (ResultMap resultMap : resultMaps) {mappedStatement.hasNestedResultMaps = mappedStatement.hasNestedResultMaps || resultMap.hasNestedResultMaps();}return this;}public Builder statementType(StatementType statementType) {mappedStatement.statementType = statementType;return this;}public Builder resultSetType(ResultSetType resultSetType) {mappedStatement.resultSetType = resultSetType == null ? ResultSetType.DEFAULT : resultSetType;return this;}}
最后就提供一个build方法,返回构建完成的对象就好了。
public MappedStatement build() {assert mappedStatement.configuration != null;assert mappedStatement.id != null;assert mappedStatement.sqlSource != null;assert mappedStatement.lang != null;mappedStatement.resultMaps = Collections.unmodifiableList(mappedStatement.resultMaps);return mappedStatement;}
在客户端使用的时候,先创建一个Builder,然后链式的调用一堆方法,最后再调用一次build()方法,需要的对象就有了,这就是构造器模式的应用。
MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType).resource(resource).fetchSize(fetchSize).timeout(timeout).statementType(statementType).keyGenerator(keyGenerator).keyProperty(keyProperty).keyColumn(keyColumn).databaseId(databaseId).lang(lang).resultOrdered(resultOrdered).resultSets(resultSets).resultMaps(getStatementResultMaps(resultMap, resultType, id)).resultSetType(resultSetType).flushCacheRequired(valueOrDefault(flushCache, !isSelect)).useCache(valueOrDefault(useCache, isSelect)).cache(currentCache);ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);MappedStatement statement = statementBuilder.build();configuration.addMappedStatement(statement);return statement;
