建造者模式

两盒软妹~` 提交于 2020-02-10 09:02:11
 /// <summary>
    /// 建造者模式:的基类。
    /// 它要求建造过程必须是稳定的。这是与装饰模式的区别
    /// </summary>
    abstract class Builder
    {
        public abstract void BuilderPartA();
        public abstract void BuilderPartB();
        public abstract Product GetResult();
    }

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

        public override void BuilderPartA()
        {
            p.Add("part A");
        }

        public override void BuilderPartB()
        {
            p.Add("part B");
        }

        public override Product GetResult()
        {
            return p;
        }
    }

    /// <summary>
    /// 具体建造者2,它亦有它自己固定的构造过程
    /// </summary>
    class ConcreteBuilder2 : Builder
    {
        private Product product = new Product();

        public override void BuilderPartA()
        {
            product.Add("part x");
        }

        public override void BuilderPartB()
        {
            product.Add("part Y");
        }

        public override Product GetResult()
        {
            return product;
        }
    }

    /// <summary>
    /// 指挥者类,它指示具体调用那个建造者
    /// </summary>
    class Director
    {
        /// <summary>
        /// 构造产品的具体步骤
        /// </summary>
        public void Constructor(Builder buider)
        {
            buider.BuilderPartA();
            buider.BuilderPartB();
        }
    }

    /// <summary>
    /// 需要构建的对象类
    /// </summary>
    class Product
    {
        List<string> parts = new List<string>();

        public void Add(string partName)
        {
            parts.Add(partName);
        }

        public void Show()
        {
            foreach (var item in parts)
            {
                Console.WriteLine(item);
            }
        }
    }

    class TestBuilder
    {
        public void Run()
        {
            ConcreteBuilder buider1 = new ConcreteBuilder();
            Director director = new Director();
            director.Constructor(buider1);
            Product p = buider1.GetResult();
            p.Show();

            ConcreteBuilder2 buider2 = new ConcreteBuilder2();
            director.Constructor(buider2);
            Product p2 = buider2.GetResult();
            p2.Show();
        }
    }

 

建造者模式

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!