建造者模式(Builder Pattern)是一种创建型设计模式,它提供了一种创建复杂对象的最佳方式。这种模式能够让分步骤创建复杂对象,并允许只通过必要的步骤来构建对象。建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
建造者模式通常在以下情况下使用:
要查看建造者模式的UML图,请访问dofactory网站。
让通过一个C#示例来理解建造者模式。
Director类负责协调构建过程。
public class Director
{
public void Construct(HouseBuilder houseBuilder)
{
houseBuilder.BuildFloor();
houseBuilder.BuildWalls();
houseBuilder.BuildDoors();
houseBuilder.BuildWindows();
}
}
HouseBuilder是一个抽象类,定义了构建房屋的接口。
public abstract class HouseBuilder
{
protected House _house;
public House House
{
get { return _house; }
}
public abstract void BuildDoors();
public abstract void BuildWindows();
public abstract void BuildWalls();
public abstract void BuildFloor();
}
HousePart类表示房屋的一部分,House类表示整个房屋。
public class HousePart
{
private string _strPartName;
public string PartName
{
get { return _strPartName; }
}
public HousePart(string name)
{
_strPartName = name;
}
}
public class House
{
private string _material;
private List _houseParts;
public string Material
{
get { return _material; }
}
public House(string material)
{
_material = material;
_houseParts = new List();
}
public void AddPart(HousePart part)
{
_houseParts.Add(part);
}
}
public class GlassHouseBuilder : HouseBuilder
{
public override void BuildFloor()
{
_house = new House("glass");
House.AddPart(new HousePart("stone floor"));
}
public override void BuildWalls()
{
House.AddPart(new HousePart(House.Material + " walls"));
}
public override void BuildDoors()
{
House.AddPart(new HousePart("wood doors"));
}
public override void BuildWindows()
{
House.AddPart(new HousePart(House.Material + " windows"));
}
}
public class WoodHouseBuilder : HouseBuilder
{
public override void BuildFloor()
{
_house = new House("wood");
House.AddPart(new HousePart(House.Material + " floor"));
}
public override void BuildWalls()
{
House.AddPart(new HousePart(House.Material + " walls"));
}
public override void BuildDoors()
{
House.AddPart(new HousePart("iron doors"));
}
public override void BuildWindows()
{
House.AddPart(new HousePart("glass windows"));
}
}