Builder 模式是一步一步创建一个复杂对象的创建型模式,它允许用户在不知道内部构建细节的情况下,可以更精细的控制对象的构造流程。该模式是为了将构建复杂对象的过程和它的部件解耦,使得构建过程和部件的表示隔离开来,两者之间的耦合。
使用场景:
1.相同的方法,不同的执行顺序,产生不同的事件结果。(View的封装,对外暴露的方法不同)
2.初始化一个对象特别复杂,如参数特别多且很多都具有默认参数时
示例代码:
public class BuilderTest {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder {
// Required parameters
private final int servingSize;
private final int servings;
// Optional parameters - initialized to default values
private int calories = 0;
private int fat = 0;
private int sodium = 0;
private int carbohydrate = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val) {
calories = val;
return this;
}
public Builder fat(int val) {
fat = val;
return this;
}
public Builder sodium(int val) {
sodium = val;
return this;
}
public Builder carbohydrate(int val) {
carbohydrate = val;
return this;
}
public BuilderTest build() {
return new BuilderTest(this);
}
}
private BuilderTest(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
carbohydrate = builder.carbohydrate;
}
public static void main(String[] args) {
BuilderTest cocaCola = new BuilderTest.Builder(240, 8)
.calories(100).sodium(35).carbohydrate(27).build();
}
}
IntelliJ IDEA 快速生成 Builder 样板代码
在 IntelliJ IDEA Plugin 库中有一个名叫 Builder Generator 的插件,该插件可以像生成 Getting/Setting 一样对当前类生成 Builder 样板代码。
本文由个人 hexo 博客 co2fe.com 迁移
date: 2018-09-18 15:13:06