設計模式:建造模式
來源:程序員人生 發布時間:2015-01-14 09:11:50 閱讀次數:4031次
原文地址:http://leihuang.org/2014/12/03/builder/
Creational 模式
物件的產生需要消耗系統資源,所以如何有效力的產生、管理 與操作物件,1直都是值得討論的課題, Creational 模式即與物件的建立相干,在這個分類下的模式給出了1些指點原則及設計的方向。下面羅列到的全屬于Creational 模式
- Simple Factory 模式
- Abstract Factory 模式
- Builder 模式
- Factory Method 模式
- Prototype 模式
- Singleton 模式
- Registry of Singleton 模式
出現的問題
The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.
當構造函數的參數非常多時,并且有多個構造函數時,情況以下:
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) {...}
Pizza(int size, boolean cheese, boolean pepperoni ,boolean bacon) { ... }
This is called the Telescoping Constructor Pattern. 下面還有1種解決方法叫javabean模式:
Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
Javabeans make a class mutable even if it is not strictly necessary. So javabeans require an extra effort in handling thread-safety(an immutable class is always thread safety!).詳見:JavaBean
Pattern
建造模式解決該問題
<span style="font-weight: normal;">public class Pizza {
// 必須的
private final int size;
// 可有可無的
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
// required
private final int size;
// optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
//由于size時必須的,所以設置為構造函數的參數
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);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}</span>
注意到現在Pizza是1個immutable class,所以它是線程安全的。又由于每個Builder's setter方法都返回1個Builder對象,所以可以串連起來調用。以下
Pizza pizza = new Pizza.Builder(12)
.cheese(true)
.pepperoni(true)
.bacon(true)
.build();
由上面我們可以知道,建造模式,給了用戶更大的自由,可以任選參數.
2014⑴1-09 18:21:17
Brave,Happy,Thanksgiving !
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈