java建造者模式代码
时间: 2024-01-02 14:56:23 浏览: 22
以下是一个简单的Java建造者模式代码示例:
public class Computer {
private String cpu;
private String memory;
private String hardDrive;
private String graphicsCard;
private Computer(ComputerBuilder builder) {
this.cpu = builder.cpu;
this.memory = builder.memory;
this.hardDrive = builder.hardDrive;
this.graphicsCard = builder.graphicsCard;
}
public String getCpu() {
return cpu;
}
public String getMemory() {
return memory;
}
public String getHardDrive() {
return hardDrive;
}
public String getGraphicsCard() {
return graphicsCard;
}
public static class ComputerBuilder {
private String cpu;
private String memory;
private String hardDrive;
private String graphicsCard;
public ComputerBuilder() {
}
public ComputerBuilder cpu(String cpu) {
this.cpu = cpu;
return this;
}
public ComputerBuilder memory(String memory) {
this.memory = memory;
return this;
}
public ComputerBuilder hardDrive(String hardDrive) {
this.hardDrive = hardDrive;
return this;
}
public ComputerBuilder graphicsCard(String graphicsCard) {
this.graphicsCard = graphicsCard;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
// 使用方法
Computer computer = new Computer.ComputerBuilder()
.cpu("Intel i7")
.memory("16GB")
.hardDrive("1TB SSD")
.graphicsCard("Nvidia RTX 3070")
.build();