本帖最后由 惜 于 2019-1-1 20:23 编辑
三 、 程序举例 :
该程序演示了 Builder 模式一步一步完成构件复杂产品的过程。用户可以控制生成过程以及生成不同对象。
[C#] 纯文本查看 复制代码 // Builder pattern -- Structural example
using System;
using System.Collections;
// "Director"
class Director
{
// Methods
public void Construct( Builder builder )
{
builder.BuildPartA();
builder.BuildPartB();
}
}
// "Builder"
abstract class Builder
{
// Methods
abstract public void BuildPartA();
abstract public void BuildPartB();
abstract public Product GetResult();
}
// "ConcreteBuilder1"
class ConcreteBuilder1 : Builder
{
// Fields
private Product product;
// Methods
override public void BuildPartA()
{
product = new Product();
product.Add( "PartA" );
}
override public void BuildPartB()
{
product.Add( "PartB" );
}
override public Product GetResult()
{
return product;
}
}
// "ConcreteBuilder2"
class ConcreteBuilder2 : Builder
{
// Fields
private Product product;
// Methods
override public void BuildPartA()
{
product = new Product();
product.Add( "PartX" );
}
override public void BuildPartB()
{
product.Add( "PartY" );
}
override public Product GetResult()
{
return product;
}
}
// "Product"
class Product
{
// Fields
ArrayList parts = new ArrayList();
// Methods
public void Add( string part )
{
parts.Add( part );
}
public void Show()
{
Console.WriteLine( " Product Parts -------" );
foreach( string part in parts )
Console.WriteLine( part );
}
}
/// <summary>
/// Client test
/// </summary>
public class Client
{
public static void Main( string[] args )
{
// Create director and builders
Director director = new Director( );
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
// Construct two products
director.Construct( b1 );
Product p1 = b1.GetResult();
p1.Show();
director.Construct( b2 );
Product p2 = b2.GetResult();
p2.Show();
}
}
四 、 建造者模式的活动序列 :
客户端负责创建指导者和具体建造者对象。然后,客户把具体建造者对象交给指导者。客户一声令下,指导者操
纵建造者开始创建产品。当产品创建完成后,建造者把产品返还给客户端。
|