Product类——产品类,由多个部件组成。
class Product
{IList<string> parts = new List<string>();//添加产品部件public void Add(string part){parts.Add(part);}public void Show(){foreach (string part in parts){Debug.Log("产品:"+part);}}
}
Builder类——抽象建造者类,确定产品由两个部件Part A和Part B组成,并声明一个得到产品建造
后结果的方法GetResult。
abstract class Builder
{public abstract void BuildPartA();public abstract void BuildPartB();public abstract Product GetResult();
}
Concrete Builder类,具体建造者类。
class ConcreteBuilder : Builder
{private Product product =new Product();public override void BuildPartA(){product.Add("部件x");}public override void BuildPartB(){product.Add("部件y");}public override Product GetResult(){return product;}
}
class ConcreteBuilder2 : Builder
{private Product product = new Product();public override void BuildPartA(){product.Add("部件x2");}public override void BuildPartB(){product.Add("部件y2");}public override Product GetResult(){return product;}
}
Director类指挥者类。
class Director
{public void Construct(Builder builder){builder.BuildPartA();builder.BuildPartB();}
}
客户端代码,客户不需要知道具体建造过程。
private void Start(){Director director = new Director();Builder builder = new ConcreteBuilder();Builder builder1 = new ConcreteBuilder2();director.Construct(builder);Product p = builder.GetResult();p.Show();director.Construct(builder1);Product p1 = builder1.GetResult();p1.Show();}
建造者模式是在当 创建复杂对象的算法 应该 独立于该对象的组成部分 以及 它们的装配方
式 时适用的模式。