1. 使用时机
建造者模式与工厂模式很类似,那么我们该如何选择呢?
简单来说,创建一个对象需要很多步骤时,选择建造者模式。创建一个对象只需要一个方法时,选择工厂模式。这是因为建造者模式的关注点是方法调用顺序,而工厂模式的关注点是创建产品,而且建造者遵循了最少知道原则,即将构建产品顺序和细节封装在建造者内部,用户无需知道产品的构建细节。
2. 源码案例
JDK
- StringBuilder#append
- StringBuffer#append 加锁,保证线程安全
Guava
- Immutable#copyOf
Lombok
- @Builder
/**
* @Author shaohsiung
* @Date 2019/7/26 21:53
* @Hint 建造者模式+静态内部类实现链式构造user对象
**/
@ToString
public class User {
private Long id;
private String userName;
private String password;
public User build(UserBuilder userBuilder) {
this.id = userBuilder.id;
this.userName = userBuilder.userName;
this.password = userBuilder.password;
return this;
}
public static UserBuilder builder() {
return new UserBuilder();
}
public static class UserBuilder {
private Long id;
private String userName;
private String password;
public UserBuilder id(Long id) {
this.id = id;
return this;
}
public UserBuilder userName(String userName) {
this.userName = userName;
return this;
}
public UserBuilder password(String password) {
this.password = password;
return this;
}
public User build() {
return new User().build(this);
}
}
}
Spring
- BeanDefinitionBuilder
Mybatils
- SqlSessionFactoryBuilder
- XmlConfigBuilder