设计模式:建造者模式

建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

设计模式:建造者模式_第1张图片

namespace Builder
{
    public class Product
    {
        IList<string> parts = new List<string>();
        public void Add(string part)
        {
            parts.Add(part);
        }
        public void Show()
        {
            Console.WriteLine("\n产品 创建 ---");
            foreach(string part in parts)
            {
                Console.WriteLine(part);
            }
        }
    }
    public abstract class Builder
    {
        public abstract void BuildPartA();
        public abstract void BuildPartB();
        public abstract Product GetResult();
    }
    public class ConcreteBuilder1 : Builder
    {
        private Product product = new Product();
        public override void BuildPartA()
        {
            product.Add("部件A");
        }

        public override void BuildPartB()
        {
            product.Add("部件B");
        }

        public override Product GetResult()
        {
            return product;
        }
    }
    public class ConcreteBuilder2 : 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;
        }
    }
    public class Director
    {
        public void Construct(Builder builder)
        {
            builder.BuildPartA();
            builder.BuildPartB();
        }
    }
}
View Code

测试代码:

            Builder.Director director = new Builder.Director();
            Builder.Builder b1 = new Builder.ConcreteBuilder1();
            Builder.Builder b2 = new Builder.ConcreteBuilder2();
            director.Construct(b1);
            Builder.Product p1 = b1.GetResult();
            p1.Show();
            director.Construct(b2);
            Builder.Product p2 = b2.GetResult();
            p2.Show();
View Code

 

你可能感兴趣的:(设计模式:建造者模式)