建造者模式
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(); } }
结果: