写一个建造者模式的demo
时间: 2024-05-15 18:14:50 浏览: 18
好的,我可以为您提供一个建造者模式的demo,以下是代码:
```java
public class Computer {
private String cpu;
private String motherboard;
private int memory;
private String hardDrive;
private String graphicsCard;
private String inputDevice;
private String outputDevice;
public Computer(ComputerBuilder builder) {
this.cpu = builder.cpu;
this.motherboard = builder.motherboard;
this.memory = builder.memory;
this.hardDrive = builder.hardDrive;
this.graphicsCard = builder.graphicsCard;
this.inputDevice = builder.inputDevice;
this.outputDevice = builder.outputDevice;
}
public String getCpu() {
return cpu;
}
public String getMotherboard() {
return motherboard;
}
public int getMemory() {
return memory;
}
public String getHardDrive() {
return hardDrive;
}
public String getGraphicsCard() {
return graphicsCard;
}
public String getInputDevice() {
return inputDevice;
}
public String getOutputDevice() {
return outputDevice;
}
public static class ComputerBuilder {
private String cpu;
private String motherboard;
private int memory;
private String hardDrive;
private String graphicsCard;
private String inputDevice;
private String outputDevice;
public ComputerBuilder(String cpu, String motherboard, int memory) {
this.cpu = cpu;
this.motherboard = motherboard;
this.memory = memory;
}
public ComputerBuilder hardDrive(String hardDrive) {
this.hardDrive = hardDrive;
return this;
}
public ComputerBuilder graphicsCard(String graphicsCard) {
this.graphicsCard = graphicsCard;
return this;
}
public ComputerBuilder inputDevice(String inputDevice) {
this.inputDevice = inputDevice;
return this;
}
public ComputerBuilder outputDevice(String outputDevice) {
this.outputDevice = outputDevice;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
```
在这个例子中,我们创建了一个Computer类,作为建造者模式的产品。该类包含了一些计算机组件的信息,比如处理器、主板、内存、硬盘等等。为了创建这个类,我们需要先创建一个ComputerBuilder类,这个类包含了与Computer类相关的信息,并提供一些方法来设置不同的组件。最后,我们使用ComputerBuilder类的方法build()来创建Computer对象,这个对象是由Builder模式组装的。