建造者模式(Builder),也叫生成器模式,将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
建造小人的代码实现
abstract class PersonBuilder
{
protected Graphics g;
protected Pen p;
public PersonBuild(Graphics g,Pen p)
{
this.g = g;
this.p = p;
}
public abstract void BuildHead();
public abstract void BuildBody();
public abstract void BuildOther();
}
class PersonThinBuilder : PersonBuilder
{
public PersonThinBuilder(Graphics g,Pen p) : base(g,p)
{}
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 BuildOther()
{
g.DrawRectangle(p,60,50,10,50);
}
}
//建造的指挥者类
class PersonDirector
{
private PersonBuilder pb;
public PersonDirector(PersonBuilder pb)
{
this.pb = pb;
}
public void CreatePerson()
{
pb.BuildHead();
pb.BuildBody();
pb.BuildOther();
}
}
PersonDirector 类的目的就是根据用户的选择来一步一步建造小人,而建造的过程在指挥者这里就完成了,用户不需要知道,而且这个过程是每一步都是是一定要做的,那就不会让少画一只手,小画一条腿的问题出现。
---客户端代码---
Pen p = new Pen(Color.Yellow);
PersonThinBuilder ptb = new PersonThinBuilder(pictureBox1.CreateGraphics(),p);
PersonDirector pdThin = new PersonDirector(ptd);
pdThin.CreatePerson();
建造者模式结构图:
建造者模式基本代码
Product 类
class Product
{
IList<string> parts = new List<string>();
//添加产品部件
public void Add(string part)
{
parts.Add(part);
}
public void Show()
{
Console.WriteLine("\n 产品创建 ---");
foreach(string part in parts)
{
Console.WriteLine(part);
}
}
}
Builder类 抽象建造者,确定产品同两个部件PartA,PartB组成,并声明一个得到产品建造后结果的方法GetResult
abstract class Builder
{
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
class ConcreteBuilder1 : Builder
{
private Product product = new Product();
public override void BuildPartA()
{
product.Add("部件A");
}
public override void BuildPartB()
{
product.Add("部件B");
}
public override Product GetResult()
{
return product;
}
}
指挥者类
class Director
{
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
}
}
---客户端代码---
static void Main(string[] args)
{
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
director.Construct(b1);
Product p1 = b1.GetResult();
p1.Show();
Console.Read();
}
所以说,建造者模式是当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式方式时适用的模式.