建造者模式一般用于复杂对象的组装,即生成的对象可能依赖不同熟悉生成,依赖其他对象等 它强调对象的组装过程
//复杂对象
@Data public class MySqlReader { private String sql; private String name; private JdbcOptions options; }
//抽象建造者
@Component public interface IMySqlReader { /** * reader组件传来的sql语句 * * @param sql */ void builderSql(String sql); /** * reader组件名字 * * @param name */ void builderName(String name); /** * reader配置 * * @param options */ void buildOptions(JdbcOptions options); /** * 构建reader对象 * * @return */ MySqlReader builderMysqlReader(); }
//实际的建造者
@Component public class ConcreateBuilder implements IMySqlReader { MySqlReader mySqlReader; public ConcreateBuilder() { mySqlReader = new MySqlReader(); } @Override public void builderSql(String sql) { mySqlReader.setSql(sql); } @Override public void builderName(String name) { mySqlReader.setName(name); } @Override public void buildOptions(JdbcOptions jdbcOptions) { mySqlReader.setOptions(jdbcOptions); } @Override public MySqlReader builderMysqlReader() { return this.mySqlReader; } }
//导演 用于强调指定对象生成
public MySqlReader constructMySqlReader(IMySqlReader builder, String name, String sql, JdbcOptions jdbcOptions) { //指导者内部 构建实际对象 builder.builderName(name); builder.builderSql(sql); builder.buildOptions(jdbcOptions); return builder.builderMysqlReader(); }