学习设计模式,也是读码的一个乐趣。
从mybatis的基础代码,看看builder模式怎么玩
public class Environment {
private String id;
private TransactionFactory transactionFactory;
private DataSource dataSource;
public Environment(String id, TransactionFactory transactionFactory, DataSource dataSource) {
this.id = id;
this.transactionFactory = transactionFactory;
this.dataSource = dataSource;
}
private Environment() {
}
public static class Builder {
private Environment environment = new Environment();
public Builder(String id, TransactionFactory transactionManager, DataSource dataSource) {
environment.id = id;
environment.transactionFactory = transactionManager;
environment.dataSource = dataSource;
}
public Builder transactionFactory(TransactionFactory transactionFactory) {
environment.transactionFactory = transactionFactory;
return this;
}
public Builder dataSource(DataSource dataSource) {
environment.dataSource = dataSource;
return this;
}
public String id() {
return environment.id;
}
public Environment build() {
return environment;
}
}
public String getId() {
return id;
}
public TransactionFactory getTransactionFactory() {
return transactionFactory;
}
public DataSource getDataSource() {
return dataSource;
}
}
小结
这种实现builder模式的要点:
1.被构建对象,构造函数私有化
private Environment() {
}
2.public static 静态内部类
public static class Builder
3.大部分方法返回Builder本身,方便链式操作
Builder dataSource(xxx)
Builder transactionFactory(xxx)
4.通过上述复制构造后,返回真正构建的对象
public Environment build() {
return environment;
}
学而时习之 :-)