应用场景
- 对象的构建有很多必填参数,如果应用构造函数会导致参数列表过长难以使用
- 结构参数之间有依赖关系,比方设置了minAge就必须设置maxAge,且minAge小于等于maxAge
- 类的属性一旦被创立就不可变(不暴力set()办法)
类图
Person类蕴含了一个外部类Builder,负责对外裸露设置属性的办法,这些办法能够蕴含校验和初始化规定,属性之前的依赖规定能够放到最终调用的build()办法中校验
代码实现
public class Person { private Long id; private String name; private Integer minAge; private Integer maxAge; private Person() { } public static class Builder { private Person person = new Person(); public Builder id(Long id) { person.id = id; return this; } public Builder name(String name) { person.name = name; return this; } public Builder minAge(Integer minAge) { person.minAge = minAge; return this; } public Builder maxAge(Integer maxAge) { person.maxAge = maxAge; return this; } public Person build() { if (person.minAge != null && person.maxAge != null) { if (person.minAge < 0) { throw new IllegalArgumentException("minAge必须大于等于0"); } if (person.maxAge <= person.minAge) { throw new IllegalArgumentException("maxAge必须大于等于minAge"); } } else if ((person.minAge == null && person.maxAge != null) || (person.minAge != null && person.maxAge == null)) { throw new IllegalArgumentException("minAge和maxAge必须同时设置"); } return person; } }}
与工厂模式有何区别?
- 工厂模式是用来创立不同然而相干类型的对象(继承同一父类或者接口的一组子类),由给定的参数来决定创立哪种类型的对象。
- 建造者模式是用来创立一种类型的简单对象,通过设置不同的可选参数,“定制化”地创立不同的对象。