建造者模式
static void Main(string[] args)
{
/*建造者模式,适合创建复杂对象,与工厂模式的关注点不一样,建造者重点关注,对象过程的创建
*
*
*
*/
{
// 创建 福特 车 注重每个过程的建造
BuilderFord builder = new BuilderFord();
builder.BuilderEngin();
builder.BuilderWheels();
builder.BuilderGearbox();
builder.CreateCar();
}
{
// 创建 BYD
BuilderByd builder = new BuilderByd();
builder.BuilderEngin();
builder.BuilderWheels();
builder.BuilderGearbox();
builder.CreateCar();
}
{
// 这里进一步 进行抽象
BuilderByd builderByd = new BuilderByd();
IBuilder builder = new BuilderFactory(builderByd);
builder.GetCar();
}
Console.WriteLine("Hello World!");
}
public class BuilderFactory : IBuilder { private AbstructBuilder _builder = default(AbstructBuilder); public BuilderFactory(AbstructBuilder builder) => this._builder = builder; public void GetCar()=> this._builder.CreateCar(); } public interface IBuilder { void GetCar(); }
public class BuilderFord : AbstructBuilder { private Wheels _wheels = default(Wheels); private Enginer _enginer = default(Enginer); private Gearbox _gearbox = default(Gearbox); public void BuilderWheels() { _wheels = new Wheels(); } public void BuilderEngin() { _enginer = new Enginer(); } public void BuilderGearbox() { _gearbox = new Gearbox(); } public override void CreateCar() { // 使用上面三个对象 Console.WriteLine($"{_enginer}{_wheels}{_gearbox}"); } }
public abstract class AbstructBuilder { public abstract void CreateCar(); }