码迷,mamicode.com
首页 > Windows程序 > 详细

C# 设计模式(5)建造者模式

时间:2020-12-05 10:57:55      阅读:15      评论:0      收藏:0      [点我收藏+]

标签:ogr   builder   set   write   ati   sha   namespace   流程   image   

建造者模式

1. 复杂对象创建,包含多步骤

2. 建造流程相对固定

代码实现:造车

模型:

namespace BuilderPattern.Models
{
    public class Engine
    {
        public string Name { get; set; }
    }
    public class Wheel
    {
        public string Name { get; set; }
    }
    public class Light
    {
        public string Name { get; set; }
    }
    public class Car
    {
        public Car(Engine engine,Wheel wheel,Light light)
        {
            
        }
        public string Name { get; set; }
    }
}

建造者:

    public abstract class AbstractBuilder
    {
       public abstract void BuildEngine();
       public abstract void BuildWheel();
       public abstract void BuildLight();
       public abstract Car BuildCar();
    }
    public class BuilderTesla:AbstractBuilder
    {
        private Engine _engine = null;
        private Wheel _wheels = null;
        private Light _lights = null;

        public override void BuildEngine()
        {
            _engine = new Engine(){Name = "Tesla_Engine"};
            Console.WriteLine($"{this.GetType().Name} build {_engine.Name}");
        }

        public override void BuildWheel()
        {
            _wheels = new Wheel() { Name = "Tesla_Wheels" };
            Console.WriteLine($"{this.GetType().Name} build {_wheels.Name}");
        }

        public override void BuildLight()
        {
            _lights = new Light() { Name = "Tesla_Light" };
            Console.WriteLine($"{this.GetType().Name} build {_lights.Name}");
        }

        public override Car BuildCar()
        {
            var car = new Car(_engine,_wheels,_lights) { Name = "Tesla_Model Y" };
            Console.WriteLine($"{this.GetType().Name} build {car.Name}");
            return car;
        }
    }

导演:

    public class Director
    {
        private readonly AbstractBuilder _abstractBuilder;

        public Director(AbstractBuilder abstractBuilder)
        {
            _abstractBuilder = abstractBuilder;
        }

        public Car GetCar()
        {
            _abstractBuilder.BuildEngine();
            _abstractBuilder.BuildWheel();
            _abstractBuilder.BuildLight();

           var car = _abstractBuilder.BuildCar();

           return car;
        }
    }

上层调用:

    class Program
    {
        static void Main(string[] args)
        {
            BuilderTesla builderTesla = new BuilderTesla();
            Director director = new Director(builderTesla);
            director.GetCar();
        }
    }

结果:

技术图片

 

C# 设计模式(5)建造者模式

标签:ogr   builder   set   write   ati   sha   namespace   流程   image   

原文地址:https://www.cnblogs.com/YourDirection/p/14067560.html

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