Java设计模式<建造者模式>
意图
将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。
解决原子操作不经常变化,而组合经常变化
优点
建造者独立,易扩展
便于控制细节风险
缺点
原子操作必须有共同点,有范围限制
如果变化复杂,就会有很多建造者类
现实生活场景
主要介绍一下通过builder实现流式编程
应用场景
目前是SOA兴起的时代,所以各个模块之间API调用,通过在接口层面实现参数的校验
Demo 创建一个Person类
public class Person {
private final String name;
private final float height;
private final int weight;
public static Builder param() {
return new Builder();
}
public Person(Builder builder) {
this.name = builder.name;
this.height = builder.height;
this.weight = builder.weight;
}
public String getName() {
return name;
}
public float getHeight() {
return height;
}
public int getWeight() {
return weight;
}
static class Builder {
private String name;
private float height;
private int weight;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setHeight(float height) {
this.height = height;
return this;
}
public Builder setWeight(int weight) {
this.weight = weight;
return this;
}
public Person build(){
if(null == name || "".equals(name)){
throw new IllegalArgumentException("name can not be null");
}
return new Person(this);
}
}
}
测试类
public class DemoMain2 {
public static void main(String[] args) {
Person person = Person.param().
setName("jeffy").
setHeight(180l).
setWeight(75)
.build();
}
}
网友评论