What does Builder Pattern looks like
new MaterialDialog.Builder(this)
.title(R.string.title)
.content(R.string.content)
.positiveText(R.string.agree)
.negativeText(R.string.disagree)
.show();
In OkHttp
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Also see in Android Source Code - AlertDialog, Notification...
What is Builder Pattern
The builder pattern is an object creation software design pattern.
首先试伙,建造者(生成器)模式是一種構(gòu)建對象的設(shè)計模式于样。
- 它可以將復(fù)雜對象的建造過程抽象出來(抽象類別)潘靖,分離對象的表示和構(gòu)建, 使這個抽象過程的不同實現(xiàn)方法可以構(gòu)造出不同表現(xiàn)(屬性)的對象糊余。
When use Builder Pattern
When would you use the Builder Pattern? [closed]
The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.
一般的構(gòu)造方法
- Telescoping Constructor Pattern
Pizza(int size) { ... } Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }
- parameters limitation
- difficult to remember required order of the parameters
- JavaBean Pattern
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
- The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.
The better alternative is to use the Builder Pattern.
How to use Builder Pattern
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
}
- Because the Builder's setter methods return the Builder object they are able to be chained.
Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
- This results in code that is easy to write and very easy to read and understand.
- This pattern is flexible and it is easy to add more parameters to it in the future.It might be worthwhile in the first place if you suspect you may be adding more parameters in the future.
Conclusion
- 大量參數(shù)
- 良好的擴(kuò)展性
- 通用性
- 造輪子
Reference
- Effective Java, 2nd Edition by Joshua Bloch.
- Stack Overflow - When would you use the Builder Pattern? [closed]
- Wikipedia - Builder Pattern