将一个复杂对象的构建与它的表示分开,使得同样的构建过程可以创建不同的表示。如果我们用了建造者模式,那么用户就只需要指定需要建造的类型就可以得到它们,而具体建造的过程和细节就不需要知道了。(过程是稳定的,但是具体的细节是不同的)
建造者模式中一个很重要的类,指挥者(Director),用它来控制建造过程,也用它来隔离用户和建造过程的关联。
abstract class PersonBuilder { //把过程稳定住 protected Graphics g; protected Pen p; public PersonBuilder(Graphics g,Pen p) { this.g = g; this.p = p; } public abstract void BuildHead(); public abstract void BuildBody(); public abstract void BuildArmLeft(); public abstract void BuildArmRight(); public abstract void BuildLegLeft(); public abstract void BuildLegRight(); }
class PersonThinBuilder:PersonBuilder { //具体的细节 public PersonThinBuilder(Graphics g,Pen p) : base(g, p)//base用于在派生类中访问重写的基类成员,Base 是子类中引用父类 { } public override void BuildHead() { g.DrawEllipse(p, 50, 20, 30, 30); } public override void BuildBody() { g.DrawRectangle(p, 60, 50, 10, 50); } public override void BuildArmLeft() { g.DrawLine(p, 60, 50, 40, 100); } public override void BuildArmRight() { g.DrawLine(p, 70, 50, 90, 100); } public override void BuildLegLeft() { g.DrawLine(p, 60, 100, 45, 150); } public override void BuildLegRight() { g.DrawLine(p, 70, 100, 85, 150); } }
class PersonDirector { private PersonBuilder pb; public PersonDirector(PersonBuilder pb)//用户告诉指挥者需要什么样的小人 { this.pb = pb; } public void CreatePerson() { pb.BuildHead(); pb.BuildBody(); pb.BuildArmLeft(); pb.BuildArmRight(); pb.BuildLegLeft(); pb.BuildLegRight(); } }