1.生成器模式:
将一个复杂对象的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。
2.生成器模式应用场景:
一个复杂的对象的创建,通常由各个部分的子对象构成,由于需求的变化,各个子对象经常发生变化。
3.举例
IProduct.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Builder
{
interface IProduct
{
string PartA
{
get;
set;
}
string PartB
{
get;
set;
}
}
}
ConcreteProduct.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Builder
{
class ConcreteProduct:IProduct
{
private string m_partA, m_partB;
public string PartA
{
get { return m_partA; }
set { m_partA = value; }
}
public string PartB
{
get { return m_partB; }
set { m_partB = value; }
}
public override string ToString()
{
return m_partA + m_partB;
}
}
}
IBuilder.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Builder
{
interface IBuilder
{
void BuilderPartA();
void BuilderPartB();
IProduct Product{get;}
}
}
ConcreteBuilder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Builder
{
class ConcreteBuilder:IBuilder
{
private IProduct m_product;
public ConcreteBuilder()
{
m_product = new ConcreteProduct();
}
public void BuilderPartA()
{
m_product.PartA = "Part A is complete.\r\n";
}
public void BuilderPartB()
{
m_product.PartB = "Part B is complete.\r\n";
}
public IProduct Product
{
get
{
return this.m_product;
}
}
}
}
Director.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Builder
{
class Director
{
private IBuilder m_builder;
public Director(IBuilder builder)
{
m_builder = builder;
}
public void Construct()
{
m_builder.BuilderPartA();
m_builder.BuilderPartB();
}
}
}
ClientMain.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Builder
{
class Program
{
static void Main(string[] args)
{
IBuilder builder = new ConcreteBuilder();
Director director = new Director(builder);
director.Construct();
Console.WriteLine(builder.Product.ToString());
}
}
}