逻辑代码:
1 abstract class PersonBuilder 2 { 3 protected Graphics g; 4 protected Pen p; 5 6 public PersonBuilder(Graphics g, Pen p) 7 { 8 this.g = g; 9 this.p = p; 10 } 11 12 public abstract void BuildHead(); 13 public abstract void BuildBody(); 14 public abstract void BuildArmLeft(); 15 public abstract void BuildArmRight(); 16 public abstract void BuildLegLeft(); 17 public abstract void BuildLegRight(); 18 } 19 20 class PersonThinBuilder : PersonBuilder 21 { 22 public PersonThinBuilder(Graphics g, Pen p) : base(g, p) 23 {} 24 25 public override void BuildHead() 26 { 27 g.DrawEllipse(p, 50, 20, 30, 30); 28 } 29 30 public override void BuildBody() 31 { 32 g.DrawRectangle(p, 60, 50, 10, 50); 33 } 34 35 public override void BuildArmLeft() 36 { 37 g.DrawLine(p, 60, 50, 40, 100); 38 } 39 40 public override void BuildArmRight() 41 { 42 g.DrawLine(p, 70, 50, 90, 100); 43 } 44 45 public override void BuildLegLeft() 46 { 47 g.DrawLine(p, 60, 100, 45, 150); 48 } 49 50 public override void BuildLegRight() 51 { 52 g.DrawLine(p, 70, 100, 85, 150); 53 } 54 } 55 56 class PersonFatBuilder : PersonBuilder 57 { 58 public PersonFatBuilder(Graphics g, Pen p) : base(g, p) 59 {} 60 61 public override void BuildHead() 62 { 63 g.DrawEllipse(p, 150, 20, 30, 30); 64 } 65 66 public override void BuildBody() 67 { 68 g.DrawEllipse(p, 145, 50, 40, 50); 69 } 70 71 public override void BuildArmLeft() 72 { 73 g.DrawLine(p, 150, 50, 130, 100); 74 } 75 76 public override void BuildArmRight() 77 { 78 g.DrawLine(p, 180, 50, 200, 100); 79 } 80 81 public override void BuildLegLeft() 82 { 83 g.DrawLine(p, 160, 100, 145, 150); 84 } 85 86 public override void BuildLegRight() 87 { 88 g.DrawLine(p, 170, 100, 185, 150); 89 } 90 } 91 92 class PersonDirector 93 { 94 private PersonBuilder pb; 95 public PersonDirector(PersonBuilder pb) 96 { 97 this.pb = pb; 98 } 99 public void CreatePerson() 100 { 101 pb.BuildHead(); 102 pb.BuildBody(); 103 pb.BuildArmLeft(); 104 pb.BuildArmRight(); 105 pb.BuildLegLeft(); 106 pb.BuildLegRight(); 107 } 108 }
客户端代码:
1 void Button1Click(object sender, EventArgs e) 2 { 3 Pen p = new Pen(Color.OliveDrab); 4 PersonThinBuilder ptb = new PersonThinBuilder(pictureBox1.CreateGraphics(), p); 5 PersonDirector pdThin = new PersonDirector(ptb); 6 pdThin.CreatePerson(); 7 } 8 void Button2Click(object sender, System.EventArgs e) 9 { 10 Pen p = new Pen(Color.Moccasin); 11 PersonFatBuilder pfb = new PersonFatBuilder(pictureBox1.CreateGraphics(), p); 12 PersonDirector pdFat = new PersonDirector(pfb); 13 pdFat.CreatePerson(); 14 15 }
效果跟上次一样的。