建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。(转至《大话设计模式》)。
学习这个模式后,不知觉得和之前的简单工厂模式做了对比,发现二者都是创建对象。但二者还是有所区别的,简单工厂模式是更具不同的情况创建不同的对象,
而建造者模式则主要是用于创建一些复杂的对象,这些对象内部构建间的建造顺序通常是稳定的,但对象内部
的构建通常面临复杂的变化。
建造者模式的好处就是使得建造代码与表示代码分离,由于建造模式印厂了该产品是如何组装的,所以需要改变一个产品的内部表示,只需要再定义一个具体的建造者就可以了。
下面的代码:是利用Graphics来画图。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace 建造者模式 { public class Man { private Pen p; private Graphics g; public Pen P { get { return p; } set { p = value; } } public Graphics G { get { return g; } set { g = value; } } public Man(Pen myP, Graphics myG) { this.p = myP; this.g = myG; } public virtual void buildHead() { } public virtual void buildBody() { } public virtual void buildLeftArm() { } public virtual void buildRightArm() { } public virtual void buildLeftLeg() { } public virtual void buildRightLeg() { } } public class thinMan : Man { public thinMan(Pen p, Graphics g) : base(p, g) { } 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 buildLeftArm() { G.DrawLine(P, 60, 50, 40, 100); } public override void buildRightArm() { G.DrawLine(P, 70, 50, 90, 100); } public override void buildLeftLeg() { G.DrawLine(P, 60, 100, 45, 150); } public override void buildRightLeg() { G.DrawLine(P, 70, 100, 85, 150); } } public class fatMan:Man { public fatMan(Pen p, Graphics g) : base(p, g) { } public override void buildHead() { G.DrawEllipse(P, 50, 20, 30, 30); } public override void buildBody() { G.DrawEllipse(P, 45, 50, 40, 50); } public override void buildLeftArm() { G.DrawLine(P, 50, 50, 30, 100); } public override void buildRightArm() { G.DrawLine(P, 80, 50, 100, 100); } public override void buildLeftLeg() { G.DrawLine(P, 60, 100, 45, 150); } public override void buildRightLeg() { G.DrawLine(P, 70, 100, 85, 150); } } public class manBuilder { Man m; public manBuilder(Man mM) { this.m = mM; } public void Show() { m.buildHead(); m.buildBody(); m.buildLeftArm(); m.buildRightArm(); m.buildLeftLeg(); m.buildRightLeg(); } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Pen p = new Pen(Color.Blue); Graphics gThin = pictureBox1.CreateGraphics(); thinMan tMan = new thinMan(p, gThin); manBuilder m = new manBuilder(tMan); m.Show(); Graphics gFat = pictureBox2.CreateGraphics(); fatMan fMan = new fatMan(p, gFat); manBuilder m1 = new manBuilder(fMan); m1.Show(); } } }
运行结果: