建造者模式
建造者模式:是在当创建复杂对象的算法,应该独立于改对象的组成部分以及它们的装配方式的使用模式,好处是使得建造者代码与表示代码分离。
结构图:
需要建造的对象(一般是复杂对象):
class Product
{
IList<string> parts = new List<string>();
public void Add(string part)
{
parts.Add(part);
}
public void Show()
{
Console.WriteLine("产品创建");
foreach (string part in parts)
{
Console.WriteLine(part);
}
}
}
{
IList<string> parts = new List<string>();
public void Add(string part)
{
parts.Add(part);
}
public void Show()
{
Console.WriteLine("产品创建");
foreach (string part in parts)
{
Console.WriteLine(part);
}
}
}
建造者的抽象类:
abstract class Builder
{
public abstract void BuilderPartA();
public abstract void BuilderPartB();
public abstract Product GetResult();
}
{
public abstract void BuilderPartA();
public abstract void BuilderPartB();
public abstract Product GetResult();
}
具体的建造方式在子类实现:
class ConcreteBuilder1 : Builder
{
private Product product = new Product();
public override void BuilderPartA()
{
product.Add("部件A");
}
public override void BuilderPartB()
{
product.Add("部件B");
}
public override Product GetResult()
{
return product;
}
}
{
private Product product = new Product();
public override void BuilderPartA()
{
product.Add("部件A");
}
public override void BuilderPartB()
{
product.Add("部件B");
}
public override Product GetResult()
{
return product;
}
}
class ConcreteBuilder2 : Builder
{
private Product product = new Product();
public override void BuilderPartA()
{
product.Add("部件X");
}
public override void BuilderPartB()
{
product.Add("部件Y");
}
public override Product GetResult()
{
return product;
}
}
{
private Product product = new Product();
public override void BuilderPartA()
{
product.Add("部件X");
}
public override void BuilderPartB()
{
product.Add("部件Y");
}
public override Product GetResult()
{
return product;
}
}
但是上也只是实现了建造的方法,需要一个建造发起者(指挥官):
class Director
{
public void Construct(Builder builder)
{
builder.BuilderPartA();
builder.BuilderPartB();
}
}
{
public void Construct(Builder builder)
{
builder.BuilderPartA();
builder.BuilderPartB();
}
}
主函数调用:
class Program
{
static void Main(string[] args)
{
Director de = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
de.Construct(b1);
Product p1 = b1.GetResult();
p1.Show();
de.Construct(b2);
Product p2 = b2.GetResult();
p2.Show();
Console.ReadKey();
}
}
{
static void Main(string[] args)
{
Director de = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
de.Construct(b1);
Product p1 = b1.GetResult();
p1.Show();
de.Construct(b2);
Product p2 = b2.GetResult();
p2.Show();
Console.ReadKey();
}
}