建造者模式:
一个复杂的对象由多个分部件组成。一个复杂对象
class Product { private string partA; //定义部件,部件可以是任意类型,包括值类型和引用类型 private string partB; private string partC; public string PartA { get { return partA; } set { partA = value; } } public string PartB { get { return partB; } set { partB = value; } } public string PartC { get { return partC; } set { partC = value; } } }
abstract class Builder { //创建产品对象 protected Product product = new Product(); public abstract void BuildPartA(); public abstract void BuildPartB(); public abstract void BuildPartC(); //返回产品对象 public Product GetResult() { return product; } }
class ConcreteBuilder1 : Builder { public override void BuildPartA() { product.PartA = "A1"; } public override void BuildPartB() { product.PartB = "B1"; } public override void BuildPartC() { product.PartC = "C1"; } }
class Director { private Builder builder; public Director(Builder builder) { this.builder = builder; } public void SetBuilder(Builder builder) { this.builder = builder; } //产品构建与组装方法 public Product Construct() { builder.BuildPartA(); builder.BuildPartB(); builder.BuildPartC(); return builder.GetResult(); } }
…… Builder builder = new ConcreteBuilder1(); //可通过配置文件实现 Director director = new Director(builder); Product product = director.Construct(); ……
【2016-10-16】【坚持学习】【Day7】【建造者模式】
原文:http://www.cnblogs.com/zscmj/p/5968050.html