设计模式创建型之建造者模式

有时需要创建一个复杂对象,并且这个复杂对象由其各部分子对象通过一定的步骤组合而成。

比如我们要生产一个车,而车是由其它一些配件如引擎,车灯,轮子等组成。而且组装是有一定顺序的。代码如下:

/// <summary>
    /// 生产引擎 
    /// </summary>
    public class Engine
    {
        public Engine()
        {
            Console.WriteLine("引擎构造完成");
        }
    }
/// <summary>
        /// 生产车灯
        /// </summary>
        public Light()
        {
            Console.WriteLine("车灯生产完成");
        }
/// <summary>
    /// 轮子
    /// </summary>
    public class Wheel
    {
        public Wheel()
        {
            Console.WriteLine("车轮子构造完成");
        }
    }
/// <summary>
    /// 组装车子
    /// </summary>
    public class Car
    {
        public Car()
        {
            Console.WriteLine("车子组装完成");
        }
    }

上端调用

static void Main(string[] args)
        {
            {
                Engine engine = new Engine();
                Light light = new Light();
                Wheel wheel = new Wheel();
                Car car = new Car();
            }
        }

 

 

 这样实现 ,上端出现了太多细节,理论上来说上端调用者只是想得到一个车子是不用关心车子创建的步骤的,这时就可以考虑将这些流程步骤交给其它环节。如下:

/// <summary>
    /// 设计者 负责把配件组装成车子
    /// </summary>
    public class Designer
    {
        public Car GetCar()
        {
            Engine engine = new Engine();
            Light light = new Light();
            Wheel wheel = new Wheel();
            Car car = new Car();
            return car;
        }
    }
 class Program
    {
        static void Main(string[] args)
        {
            {
                Engine engine = new Engine();
                Light light = new Light();
                Wheel wheel = new Wheel();
                Car car = new Car();
            }

            {
                Console.WriteLine("***********************************");
                Designer designer = new Designer();
                designer.GetCar();
            }
        }
    }

总结:当创建一个类时很复杂就用工厂,如果更复杂就用建造者。

 

posted @ 2020-08-14 16:00  一叶青城  阅读(90)  评论(0编辑  收藏  举报