建造者模式java 代码实例
时间: 2023-05-16 09:07:24 浏览: 143
以下是一个简单的建造者模式 Java 代码实例:
```
public class Computer {
private String cpu;
private String gpu;
private int memory;
private int storage;
public Computer(String cpu, String gpu, int memory, int storage) {
this.cpu = cpu;
this.gpu = gpu;
this.memory = memory;
this.storage = storage;
}
public String getCpu() {
return cpu;
}
public String getGpu() {
return gpu;
}
public int getMemory() {
return memory;
}
public int getStorage() {
return storage;
}
public static class Builder {
private String cpu;
private String gpu;
private int memory;
private int storage;
public Builder setCpu(String cpu) {
this.cpu = cpu;
return this;
}
public Builder setGpu(String gpu) {
this.gpu = gpu;
return this;
}
public Builder setMemory(int memory) {
this.memory = memory;
return this;
}
public Builder setStorage(int storage) {
this.storage = storage;
return this;
}
public Computer build() {
return new Computer(cpu, gpu, memory, storage);
}
}
}
```
使用建造者模式创建一个 Computer 对象的示例代码:
```
Computer computer = new Computer.Builder()
.setCpu("Intel Core i7")
.setGpu("Nvidia GeForce RTX 3080")
.setMemory(16)
.setStorage(512)
.build();
```
这个示例中,Computer 类的构造函数是私有的,因此只能通过 Builder 类来创建 Computer 对象。Builder 类提供了一系列 set 方法来设置 Computer 对象的属性,最后调用 build 方法来创建 Computer 对象。这种方式可以避免使用过多的构造函数参数,使代码更加清晰易懂。
阅读全文