建造者模式
一、定义
建造者模式是将一个复杂的对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。创建者模式隐藏了复杂对象的创建过程,它把复杂对象的创建过程加以抽象,通过子类继承或者重载的方式,动态的创建复杂的、具有复合属性的对象。
二、例子
构造一个手机,手机包括CPU,内存,屏幕等几个部分,而CPU,内存,屏幕配置不同又有高端,低端之分。要求手机配置可以灵活搭配。
UML
三、 代码
1.Program.cs
public class Program { static void Main(string[] args) { IPhoneBuilder phoneBuilder = new PhoneBuilder(); Phone phone = phoneBuilder .BuildCpu(cpu => { cpu.Type = "8核16线程"; }) .BuildMem(mem => { mem.Type = "32G"; }) .BuildScreen(screen => { screen.Type = "10寸"; }) .Build(); phone.Show(); } }
2.IPhoneBuilder.cs
public interface IPhoneBuilder { IPhoneBuilder BuildCpu(Action<Cpu> buildCpuDelegate); IPhoneBuilder BuildMem(Action<Mem> buildMemDelegate); IPhoneBuilder BuildScreen(Action<Screen> buildScreenDelegate); Phone Build(); }
3.PhoneBuilder.cs
public class PhoneBuilder:IPhoneBuilder { private Phone _phone; private Cpu _cpu; private Mem _mem; private Screen _screen; public IPhoneBuilder BuildCpu(Action<Cpu> buildCpuDelegate) { _cpu = new Cpu(); buildCpuDelegate?.Invoke(_cpu); return this; } public IPhoneBuilder BuildMem(Action<Mem> buildMemDelegate) { _mem = new Mem(); buildMemDelegate?.Invoke(_mem); return this; } public IPhoneBuilder BuildScreen(Action<Screen> buildScreenDelegate) { _screen = new Screen(); buildScreenDelegate?.Invoke(_screen); return this; } public Phone Build() { _phone = new Phone(); _phone.Cpu = _cpu??new Cpu() { Type="4核8线程"}; _phone.Mem = _mem ?? new Mem() { Type = "8G" }; _phone.Screen = _screen ?? new Screen() { Type = "7寸" }; return _phone; } }
4.Cpu.cs
public class Cpu { public string Type { get; set; } }
5.Mem.cs
public class Mem { public string Type { get; set; } }
6.Screen.cs
public class Screen { public string Type { get; set; } }
7.Phone.cs
public class Phone { public Cpu Cpu { get; set; } public Screen Screen { get; set; } public Mem Mem { get; set; } public void Show() { Console.WriteLine("手机配置:"); Console.WriteLine($"CPU:{Cpu?.Type}"); Console.WriteLine($"内存:{Mem?.Type}"); Console.WriteLine($"屏幕:{Screen?.Type}"); } }
四、运行结果