一.介绍
建造者模式(Singleton Pattern)。属于创建型模式。将一个复杂对象的创建和它的表示分离,使得同样的构建过程可以创建不同的表示。
二.实现
举个例子,客户去买电脑,都是和电脑店的老板直接沟通的,然后老板再安排装机人员去安装电脑,最后安装完成就可以出货。这个流程符合用建造者模式去实现,安装电脑的过程都是一样的,而用同样的流程可以安装出不同的电脑。
public static void Main(string[] args) { Boss boss = new Boss(); boss.SetBuilder(new CommonBuilder()); //同样的构建过程不同的表示 boss.Delivery(); //出货,一般电脑 boss.SetBuilder(new SeniorBuilder()); boss.Delivery(); //出货,高端电脑 } /// <summary> /// 建造者模式中的指挥者 /// </summary> public class Boss { public Builder builder { get; set; } public void SetBuilder(Builder builder) { this.builder = builder; } /// <summary> /// 提货 /// </summary> public void Delivery() { Console.WriteLine(builder.GetComputer().ToString()); } } /// <summary> /// 抽象建造者 /// </summary> public abstract class Builder { public abstract string BuildCPU(); public abstract string BuildMemory(); public abstract string BuildHD(); /// <summary> /// 构建过程一般是固定的,当然也可以在子类override /// </summary> /// <returns></returns> public virtual Computer GetComputer() { return new Computer { CPU = BuildCPU(), Memory = BuildMemory(), HD = BuildHD() }; } } /// <summary> /// 具体建造者 一般电脑 /// </summary> public class CommonBuilder : Builder { public override string BuildCPU() { return "Intel 5"; } public override string BuildHD() { return "希捷 5400转 500G"; } public override string BuildMemory() { return "金士顿 ddr3 4G"; } public override Computer GetComputer() { return new Computer { CPU = BuildCPU(), Memory = BuildMemory(), HD = BuildHD() }; } } /// <summary> /// 具体建造者 高端电脑 /// </summary> public class SeniorBuilder : Builder { public override string BuildCPU() { return "Intel 7"; } public override string BuildHD() { return "SSD 1T"; } public override string BuildMemory() { return "金士顿 ddr4 16G"; } public override Computer GetComputer() { return new Computer { CPU = BuildCPU(), Memory = BuildMemory(), HD = BuildHD() }; } } /// <summary> /// 构建的产品 /// </summary> public class Computer { public string CPU { get; set; } public string Memory { get; set; } public string HD { get; set; } public override string ToString() { var newLine = System.Environment.NewLine; return $"CPU:{CPU}{newLine}内存:{Memory}{newLine}硬盘:{HD}{newLine}"; } }
三.总结
建造者模式使得建造代码和表示代码分离,可以使客户端不必知道产品组成的细节,从而降低客户端和产品之间的耦合度。
参考:https://www.cnblogs.com/guyun/p/6183795.html