建造者模式 使用场景 示例 java
时间: 2023-09-02 09:05:53 浏览: 53
建造者模式是一种创建型设计模式,它可以将复杂对象的创建过程分解成多个简单对象的创建过程,从而简化对象的创建过程。
建造者模式适用于以下场景:
1. 需要创建复杂对象,且该对象由多个组成部分构成,且这些组成部分的创建顺序或逻辑固定不变。
2. 需要创建的对象具有可变性,即需要创建多个不同的对象,但它们的组成部分大部分相同。
3. 需要在不同的场景中创建不同的对象,但是这些对象的创建流程相对固定。
下面是一个示例 Java 代码,演示如何使用建造者模式创建一个复杂对象——计算机:
```
public class Computer {
private String cpu;
private String gpu;
private String memory;
private String hardDisk;
private String monitor;
private String keyboard;
private String mouse;
private Computer(ComputerBuilder builder) {
this.cpu = builder.cpu;
this.gpu = builder.gpu;
this.memory = builder.memory;
this.hardDisk = builder.hardDisk;
this.monitor = builder.monitor;
this.keyboard = builder.keyboard;
this.mouse = builder.mouse;
}
public String getCpu() {
return cpu;
}
public String getGpu() {
return gpu;
}
public String getMemory() {
return memory;
}
public String getHardDisk() {
return hardDisk;
}
public String getMonitor() {
return monitor;
}
public String getKeyboard() {
return keyboard;
}
public String getMouse() {
return mouse;
}
public static class ComputerBuilder {
private String cpu;
private String gpu;
private String memory;
private String hardDisk;
private String monitor;
private String keyboard;
private String mouse;
public ComputerBuilder setCpu(String cpu) {
this.cpu = cpu;
return this;
}
public ComputerBuilder setGpu(String gpu) {
this.gpu = gpu;
return this;
}
public ComputerBuilder setMemory(String memory) {
this.memory = memory;
return this;
}
public ComputerBuilder setHardDisk(String hardDisk) {
this.hardDisk = hardDisk;
return this;
}
public ComputerBuilder setMonitor(String monitor) {
this.monitor = monitor;
return this;
}
public ComputerBuilder setKeyboard(String keyboard) {
this.keyboard = keyboard;
return this;
}
public ComputerBuilder setMouse(String mouse) {
this.mouse = mouse;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
// 使用建造者模式创建计算机对象
Computer computer = new Computer.ComputerBuilder()
.setCpu("Intel Core i7-9700K")
.setGpu("NVIDIA GeForce RTX 2080 Ti")
.setMemory("32GB DDR4")
.setHardDisk("1TB NVMe SSD")
.setMonitor("Dell U3419W")
.setKeyboard("Logitech G Pro X")
.setMouse("Logitech G Pro Wireless")
.build();
```
在上面的示例中,我们使用了一个静态内部类 `ComputerBuilder` 来创建计算机对象。在 `ComputerBuilder` 中,我们定义了多个方法来设置计算机的组成部分。在最后,我们使用 `build()` 方法来创建计算机对象。这样就可以实现快速创建具有可变性的、复杂的计算机对象了。