建造者模式可以将部件和其组装过程分开,一步一步创建一个复杂的对象。用户只需要指定复杂对象的类型就可以得到该对象,而无须知道其内部的具体构造细节
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BuilderStructure : MonoBehaviour
{
void Start ( )
{
Director director = new Director();
Builder b1 = new ConcreteBuilder1();
Builder b2 = new ConcreteBuilder2();
//只需要指定类型,不需要知道具体组件
director.Construct(b1);
Product p1 = b1.GetResult();
p1.Show();
director.Construct(b2);
Product p2 = b2.GetResult();
p2.Show();
}
}
/// <summary>
///分析复杂流程
/// </summary>
class Director
{
//流程
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
}
}
/// <summary>
/// 具体流程实现
/// </summary>
abstract class Builder
{
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
/// <summary>
/// The 'ConcreteBuilder1' class
/// </summary>
class ConcreteBuilder1 : Builder
{
private Product _product = new Product();
public override void BuildPartA()
{
_product.Add("PartA");
}
public override void BuildPartB()
{
_product.Add("PartB");
}
public override Product GetResult()
{
return _product;
}
}
/// <summary>
/// The 'ConcreteBuilder2' class
/// </summary>
class ConcreteBuilder2 : Builder
{
private Product _product = new Product();
public override void BuildPartA()
{
_product.Add("PartX");
}
public override void BuildPartB()
{
_product.Add("PartY");
}
public override Product GetResult()
{
return _product;
}
}
/// <summary>
/// The 'Product' class
/// </summary>
class Product
{
private List<string> _parts = new List<string>();
public void Add(string part)
{
_parts.Add(part);
}
public void Show()
{
Debug.Log("\n产品 -------");
foreach (string part in _parts)
{
Debug.Log(part);
}
}
}