码迷,mamicode.com
首页 > 其他好文 > 详细

【2016-10-16】【坚持学习】【Day7】【建造者模式】

时间:2016-10-16 23:55:05      阅读:359      评论:0      收藏:0      [点我收藏+]

标签:

建造者模式:

一个复杂的对象由多个分部件组成。一个复杂对象

 

技术分享

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!