C#设计模式-建造者模式



1.定义

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

2.UML图



3.代码

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Builder builder = new ConcreteBuilder();
            Director director = new Director(builder);
            Product product = builder.GetResult();

            Console.ReadKey();
        }
    }

    /// <summary>
    /// 指挥者
    /// </summary>
    class Director
    {
        public Director(Builder builder)
        {
            builder.BuildPartA();
            builder.BuildPartB();
            Console.WriteLine("组装Product对象!");
        }

    }

    /// <summary>
    /// 抽象建造者类
    /// </summary>
    abstract class Builder
    {
        public abstract void BuildPartA();
        public abstract void BuildPartB();
        public abstract Product GetResult();
    }

    /// <summary>
    /// 具体建造者
    /// </summary>
    class ConcreteBuilder : Builder
    {
        Product product = new Product();

        public override void BuildPartA()
        {
            //组装Product对象
        }

        public override void BuildPartB()
        {
            //组装Product对象
        }

        public override Product GetResult()
        {
            Console.WriteLine("返回Product对象!");
            return product;
        }
    }

    /// <summary>
    /// 产品父类
    /// </summary>
    class Product
    { }
}


评论: 0 | 引用: 0 | 查看次数: 4009
发表评论
登录后再发表评论!