主要是为了创建一个结构稳定的复杂的对象(游戏小人,通过建造者模式可以保证小人不会缺胳膊少腿),通过指挥者类对建造类的建造过程进行管理,保证了建造的对象结构的稳定性。 #region 建造者模式 class SmallPerson { List<string> parts = new List<string>(); string type; public SmallPerson(string type) { this.type = type; } public void Add(string part) { parts.Add(part); } public void Show() { Console.WriteLine(this.type+"的创建:"); foreach (string part in parts) { Console.Write(part); } Console.WriteLine(); } } abstract class Builder { public abstract void BuildHead(); public abstract void BuildBody(); public abstract void BuildArms(); public abstract void BuildLegs(); public abstract SmallPerson GetResult(); } class PersonMaleBuilder : Builder { private SmallPerson smallPerson = new SmallPerson("男人"); public override void BuildArms() { smallPerson.Add(" 男人胳膊 "); } public override void BuildHead() { smallPerson.Add(" 男人头部 "); } public override void BuildBody() { smallPerson.Add(" 男人身体 "); } public override void BuildLegs() { smallPerson.Add(" 男人腿部 "); } public override SmallPerson GetResult() { return smallPerson; } } class PersonFemaleBuilder : Builder { private SmallPerson smallPerson = new SmallPerson("女人"); public override void BuildArms() { smallPerson.Add(" 女人胳膊 "); } public override void BuildHead() { smallPerson.Add(" 女人头部 "); } public override void BuildBody() { smallPerson.Add(" 女人身体 "); } public override void BuildLegs() { smallPerson.Add(" 女人腿部 "); } public override SmallPerson GetResult() { return smallPerson; } } class Director //指挥者类 { public void Constructor(Builder builder) { builder.BuildHead(); builder.BuildBody(); builder.BuildArms(); builder.BuildLegs(); } } #endregion class Program { static void Main(string[] args) { #region 建造者模式 Console.WriteLine("建造者模式效果演示:"); Director dir = new Director(); Builder b1 = new PersonMaleBuilder(); Builder b2 = new PersonFemaleBuilder(); dir.Constructor(b1); dir.Constructor(b2); SmallPerson sp1 = b1.GetResult(); SmallPerson sp2 = b2.GetResult(); sp1.Show(); sp2.Show(); #endregion } }