重温设计模式 --- 建造者模式

引言

建造者模式是一种创建型设计模式,它可以将一个复杂对象的构建过程和表示分离,使得相同的构建过程可以创建不同的表示,以及不同的构建过程可以创建相同的表示

在实际的开发中,我们有时需要创建一些复杂的对象,例如包含多个组件和属性的对象,这时候如果直接在代码中创建对象,代码的可读性和可维护性都会降低。而使用建造者模式可以将对象的创建过程封装在一个建造者类中,使得代码更加清晰和易于维护。

下面我们使用C#语言来实现建造者模式。我们以创建一台电脑为例,电脑包含CPU、内存、硬盘等组件。

组件类

首先我们需要定义电脑的组件类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class CPU
{
public string Type { get; set; }
}

public class Memory
{
public int Size { get; set; }
}

public class HardDisk
{
public int Capacity { get; set; }
}

复杂目标类

定义一个电脑类,该类包含CPU、内存、硬盘等组件:

1
2
3
4
5
6
7
8
public class Computer
{
public CPU CPU { get; set; }

public Memory Memory { get; set; }

public HardDisk HardDisk { get; set; }
}

建造者类

定义一个建造者类,该类用于创建电脑对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class ComputerBuilder
{
private Computer _computer = new Computer();

public ComputerBuilder SetCPU(string type)
{
_computer.CPU = new CPU { Type = type };
return this;
}

public ComputerBuilder SetMemory(int size)
{
_computer.Memory = new Memory { Size = size };
return this;
}

public ComputerBuilder SetHardDisk(int capacity)
{
_computer.HardDisk = new HardDisk { Capacity = capacity };
return this;
}

public Computer Build()
{
return _computer;
}
}

在建造者类中,我们定义了SetCPUSetMemorySetHardDisk等方法用于设置电脑的各个组件,并且在Build方法中返回最终创建的电脑对象。

最后我们可以使用建造者类创建电脑对象:

1
2
3
4
5
6
7
var computerBuilder = new ComputerBuilder();

var computer = computerBuilder
.SetCPU("Intel Core i7")
.SetMemory(16)
.SetHardDisk(512)
.Build();

总结

通过使用建造者模式,我们将电脑的创建过程封装在了建造者类中,使得代码更加清晰和易于维护。同时,我们可以通过设置不同的组件来创建不同的电脑对象,使得代码具有更好的可扩展性和复用性。