定義
建造者模式(Builder Pattern):將復雜對象的構造與其表示分離,以便相同的構造過程可以創建不同的表示。
主要解決在軟件系統中,有時候面臨著"一個復雜對象"的創建工作,其通常由各個部分的子對象用一定的算法構成;由于需求的變化,這個復雜對象的各個部分經常面臨著劇烈的變化,但是將它們組合在一起的算法卻相對穩定。
想象一個角色扮演游戲的角色生成器。最簡單的選擇是讓計算機為您創建角色。但是,如果你想選擇角色的細節,比如職業、性別、頭發顏色等,那么角色的生成就成了一個循序漸進的過程,當所有的選擇都準備好時,這個過程就完成了。
C#例子
public class People
{
private readonly string _profession;
private readonly string _name;
private string _hairType;
private string _hairColor;
public People(Builder builder)
{
this._profession = builder.Profession;
this._name = builder.Name;
this._hairColor = builder.HairColor??"黑";
this._hairType = builder.HairType??"短發";
}
public string Show() {
return string.Format("這個人的名字是{1},職業是{0},有一頭{2}色的{3}",_profession,_name,_hairColor,_hairType);
}
}
public sealed class Builder
{
public string Profession { get; private set; }
public string Name { get; private set; }
public string HairType { get; private set; }
public string HairColor { get; private set; }
public Builder(string profession, string name)
{
if (profession == null || name == null)
{
throw new Exception("profession 和 name 不能為空");
}
this.Profession = profession;
this.Name = name;
}
public Builder WithHairType(string hairType)
{
this.HairType = hairType;
return this;
}
public Builder WithHairColor(string hairColor)
{
this.HairColor = hairColor;
return this;
}
public People Build()
{
return new People(this);
}
}
static void Main(string[] args)
{
People people1 = new Builder("廚師", "張三")
.WithHairColor("黑")
.WithHairType("波浪卷發")
.Build();
Console.WriteLine(people1.Show());
People people2 = new Builder("程序員", "李四")
.WithHairColor("白")
.Build();
Console.WriteLine(people2.Show());
Console.ReadLine();
}
建造者模式參與者:
- People:被構建的對象,一般這樣的對象構建復雜。
- Builder:建造者對象,提供分部構建People的各種方法。
建造者模式適用情形
- 創建復雜對象的算法應該獨立于組成對象的各個部分以及它們的組裝方式;
- 構造過程必須允許對構造的對象進行不同的表示。
建造者模式特點
- 允許您創建不同風格的對象,同時避免構造函數污染。當一個對象可能有多種風格時很有用。或者當有很多步驟涉及到對象的創建時。
- 與工廠模式的區別是:建造者模式更加關注與零件裝配的順序
其他
實例
- System.Text.StringBuilder
源碼地址
其他設計模式