建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的建造过程可以创建不同的表示。
1、Builder是什么?
是创建一个Product对象的各个部件指定的抽象接口。
2、ConcreteBuilder 是什么?
是具体建造者,实现Builder接口,构造和装配各个部件。
3、Director是什么?
指挥者,构建一个使用Builder接口的对象。
建造者模式代码
建造者模式是当创建复杂对象的算法应当独立于该对象的组成部分以及它们的装配方式时使用的模式。using System;
using System.Collections.Generic;
using System.Text;
namespace Builder
{
class Program
{
static void Main(string[] args)
{
Director director = new Director();
Builder builder = new ConcreteBuilder();
director.Construct(builder);
Product p1 = builder.GetResult();
p1.Show();
Console.ReadLine();
}
}
abstract class Builder
{
public abstract void BuilderA();
public abstract void BuilderB();
public abstract Product GetResult();
}
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);
}
}
}
class ConcreteBuilder : Builder
{
private Product product = new Product();
public override void BuilderA()
{
product.Add("部件A");
}
public override void BuilderB()
{
product.Add("部件B");
}
public override Product GetResult()
{
return product;
}
}
class Director
{
public void Construct(Builder builder)
{
builder.BuilderA();
builder.BuilderB();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace Builder
{
class Program
{
static void Main(string[] args)
{
Director director = new Director();
Builder builder = new ConcreteBuilder();
director.Construct(builder);
Product p1 = builder.GetResult();
p1.Show();
Console.ReadLine();
}
}
abstract class Builder
{
public abstract void BuilderA();
public abstract void BuilderB();
public abstract Product GetResult();
}
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);
}
}
}
class ConcreteBuilder : Builder
{
private Product product = new Product();
public override void BuilderA()
{
product.Add("部件A");
}
public override void BuilderB()
{
product.Add("部件B");
}
public override Product GetResult()
{
return product;
}
}
class Director
{
public void Construct(Builder builder)
{
builder.BuilderA();
builder.BuilderB();
}
}
}