2016-10-16坚持学习Day7建造者模式
Posted zscmj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2016-10-16坚持学习Day7建造者模式相关的知识,希望对你有一定的参考价值。
建造者模式:
一个复杂的对象由多个分部件组成。一个复杂对象
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建造者模式的主要内容,如果未能解决你的问题,请参考以下文章