前言
C#设计模式(4)——构建者模式(Builder Pattern)
运行结果
代码
public class Computer
{private string part1 = "CPU";private string part2 = "主板";private string part3 = "内存";private string part4 = "显卡";private string part5 = "显示器";private string part6 = "磁盘";private string part7 = "声卡";private string part8 = "网卡";public void SetPart1(string part) { Console.WriteLine($"{part1}:{part}"); }public void SetPart2(string part) { Console.WriteLine($"{part2}:{part}"); }public void SetPart3(string part) { Console.WriteLine($"{part3}:{part}"); }public void SetPart4(string part) { Console.WriteLine($"{part4}:{part}"); }public void SetPart5(string part) { Console.WriteLine($"{part5}:{part}"); }public void SetPart6(string part) { Console.WriteLine($"{part6}:{part}"); }public void SetPart7(string part) { Console.WriteLine($"{part7}:{part}"); }public void SetPart8(string part) { Console.WriteLine($"{part8}:{part}"); }
}
//构建者抽象类
public abstract class Builder
{protected Computer computer;public Builder () { this.computer = new Computer(); }public abstract void BuildPart1();public abstract void BuildPart2();public abstract void BuildPart3();public abstract void BuildPart4();public abstract void BuildPart5();public abstract void BuildPart6();public abstract void BuildPart7();public abstract void BuildPart8();public Computer GetComputer() { return computer; }
}
//构建者实体类
public class ComputerBuider : Builder
{public override void BuildPart1(){computer.SetPart1($"AMD Ryzen 7 7745HX with Radeon Graphic 八核");}public override void BuildPart2(){computer.SetPart2($"MECHERVO MRID6-23");}public override void BuildPart3(){computer.SetPart3($"32GB DDR5 4800MHz( 16GB + 16GB )");}public override void BuildPart4(){computer.SetPart4($"NVIDIA GeForce RTX 4060 Laptop GPU (8GB / 清华同方)");}public override void BuildPart5(){computer.SetPart5($"TL160ADMP19[TMA2031] (16.3英寸)");}public override void BuildPart6(){computer.SetPart6($"KINGSTON OM8PGP41024N-A0 (1024GB)");}public override void BuildPart7(){computer.SetPart7($"NVIDIA High Definition Audio");}public override void BuildPart8(){computer.SetPart8($"Intel(R) Wi-Fi 6 AX200 160MHz");}
}
// 指挥者类
public class Director
{private Builder builder;public void SetBuilder(Builder builder){this.builder = builder;}public Computer Construct(){builder.BuildPart1();builder.BuildPart2();builder.BuildPart3();builder.BuildPart4();builder.BuildPart5();builder.BuildPart6();builder.BuildPart7();builder.BuildPart8();return builder.GetComputer();}
}/** 构建者模式:Builder Pattern*/
internal class Program
{static void Main(string[] args){Director director = new Director();Builder builder = new ComputerBuider();director.SetBuilder(builder);Computer computer = director.Construct();Console.ReadLine();}
}